\")\n # print inside\n return str_content.replace(substring,inside)\n \n\n\n\nwhile '(' in str_content:\n str_content = paren(str_content)\n# print str_content\nwhile '{' in str_content:\n str_content = execute(str_content)\nfor i in tokens:\n print (i)\nprint(\"---------------------------------------------------------------------------------\" )\nprint (str_content)\n\n# for i in stack_of_events:\n# print i\n# print str_content\n# print(\"\\n\\nSET OF CURLYTOPS\")\n# print(\"-------------------------------------------------------------------------------------------\")\n# for i in curlSet:\n# print i\n# print(\"-------------------------------------------------------------------------------------------\")\n# print(\"\\n\\nSET OF STATES\")\n# print(\"___________________________________________________________________________________________\")\n# for i in State:\n# print i\n# print(\"___________________________________________________________________________________________\")","sub_path":"prev_codes/prev assignments/asignment2.py","file_name":"asignment2.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"23281452","text":"from selenium import webdriver\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport urllib.request\r\nimport os\r\nimport driver as driver\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver as wd\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nimport time\r\nimport re\r\nimport csv\r\n\r\ndriver = wd.Chrome('../webdriver/chromedriver.exe')\r\n\r\ndriver.get('https://www.instagram.com/accounts/login/?source=auth_switcher')\r\n\r\ntime.sleep(3) #웹 페이지 로드를 보장하기 위해 3초 쉬기\r\n\r\n#\r\n\r\nid = 'gg__heon'\r\npassword = 'Derek2020@'\r\nid_input = driver.find_elements_by_css_selector('#react-root > section > main > div > article > div > div > div > form > div > div > label > input')[0]\r\nid_input.send_keys(id)\r\npassword_input = driver.find_elements_by_css_selector('#react-root > section > main > div > article > div > div > div > form > div > div > label > input')[1]\r\npassword_input.send_keys(password)\r\npassword_input.submit()\r\n\r\ntime.sleep(5)\r\n\r\n#\r\n\r\ndriver.get('https://www.instagram.com/explore/tags/배달의민족')\r\n\r\ntime.sleep(5)\r\n\r\ninstagram_tags = []\r\ninstagram_tag_dates = []\r\n\r\n#driver = wd.Chrome(\"../webdriver/chromedriver.exe\")\r\n#driver.get(url)\r\ntime.sleep(5)\r\n#태그 디렉 크롤링\r\n\r\ndriver.find_element_by_css_selector('div.v1Nh3.kIKUG._bz0w').click()\r\n\r\nfor i in range(2000):\r\n time.sleep(1)\r\n try:\r\n data = driver.find_element_by_css_selector('.C7I1f.X7jCj') # C7I1f X7jCj\r\n tag_raw = data.text\r\n tags = re.findall('#[A-Za-z0-9가-힣]+', tag_raw)\r\n tag = ''.join(tags).replace(\"#\",\" \") # \"#\" 제거\r\n\r\n tag_data = tag.split()\r\n\r\n for tag_one in tag_data:\r\n instagram_tags.append(tag_one)\r\n print(instagram_tags)\r\n\r\n date = driver.find_element_by_css_selector(\"time.FH9sR.Nzb55\").text # 날짜 선택\r\n\r\n if date.find('시간') != -1 or date.find('일') != -1 or date.find('분') != -1:\r\n instagram_tag_dates.append('0주')\r\n else:\r\n instagram_tag_dates.append(date)\r\n print(instagram_tag_dates)\r\n except:\r\n instagram_tags.append(\"error\")\r\n instagram_tag_dates.append('error')\r\n try:\r\n print('--count :', i)\r\n WebDriverWait(driver, 100).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a._65Bje.coreSpriteRightPaginationArrow')))\r\n driver.find_element_by_css_selector('a._65Bje.coreSpriteRightPaginationArrow').click()\r\n print(len(instagram_tags))\r\n except:\r\n\r\n f = open('배달의민족_키워드_크롤링.txt', 'w', encoding='utf-8', newline='')\r\n z = open('배달의민족_키워드_주별언급.txt', 'w', encoding='utf-8', newline='')\r\n\r\n # 크롤링 태그 키워드 저장\r\n for x in instagram_tags:\r\n tags = x\r\n f.write(str(tags) + '\\n')\r\n f.close()\r\n # 크롤링 날짜 저장\r\n for o in instagram_tag_dates:\r\n dates = o\r\n z.write(str(dates) + '\\n')\r\n z.close()\r\n driver.close()\r\n # date = datum2.text\r\n # #print(date)\r\n time.sleep(3)\r\n\r\nprint('----마지막전---')\r\nprint(instagram_tag_dates)\r\nprint(instagram_tags)\r\n\r\nf = open('배달의민족_키워드_크롤링.txt', 'w', encoding='utf-8', newline='')\r\nz = open('배달의민족_키워드_주별언급.txt', 'w', encoding='utf-8', newline='')\r\n\r\n#크롤링 태그 키워드 저장\r\nfor x in instagram_tags:\r\n tags = x\r\n f.write(str(tags) + '\\n')\r\nf.close()\r\n#크롤링 날짜 저장\r\nfor o in instagram_tag_dates:\r\n dates = o\r\n z.write(str(dates) + '\\n')\r\nz.close()\r\ndriver.close()\r\n# csvWriter = csv.writer(f)\r\n# for i in instagram_tags:\r\n# csvWriter.writerow(i)\r\n# for z in instagram_tag_dates:\r\n# csvWriter.writerow(z)\r\n# f.close()\r\n# z.close()\r\n","sub_path":"요기요_태그크롤링_페이지네이션수정.py","file_name":"요기요_태그크롤링_페이지네이션수정.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"108484852","text":"import logging\r\nimport os\r\nimport sys\r\nimport multiprocessing\r\nimport numpy as np\r\nfrom gensim.models import Word2Vec\r\nfrom sklearn.utils import check_random_state\r\n\r\n#################### config ###################\r\nmodelfile = \"../wvmodel/size300window5sg1min_count100negative10iter50.model\"\r\nquestionfile = \"../wvmodel/questions-words-Zh.txt\"\r\n############### end of config #################\r\n\r\nlogger = logging.getLogger()\r\nlogging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')\r\nlogging.root.setLevel(level=logging.INFO)\r\nlogger.info(\"running test word2vec for model: %s\" % modelfile)\r\n\r\n\r\nclass Word2VecHelper(object):\r\n \"\"\"\r\n import word2vec from gensim\r\n \"\"\"\r\n def __init__(self, test_model=False, verify_model=True):\r\n model = Word2Vec.load(modelfile)\r\n\r\n if(test_model):\r\n acc = model.accuracy(questionfile)\r\n logger.info(\"Test model \" + modelfile + \" in \" + questionfile)\r\n\r\n self.vector_size = model.vector_size\r\n self.vocab_size = len(model.wv.vocab) + 1\r\n self.word2index = self.GetWord2Index(model)\r\n self.index2word = self.GetIndex2Word(model)\r\n self.wordvector = self.GetWordVector(model)\r\n\r\n if(verify_model):\r\n logger.info(\"Verifing imported word2vec model\")\r\n random_state = check_random_state(12)\r\n check_index = random_state.randint(low=0, high=self.vocab_size-2,size=1000)\r\n for index in check_index:\r\n word_wv = model.wv.index2word[index]\r\n word_our = self.index2word[index+1]\r\n #print(index, word_wv, word_our)\r\n assert word_wv == word_our\r\n assert model.wv.vocab[word_our].index == self.word2index[word_our] - 1\r\n assert np.array_equal(model.wv[word_our], self.wordvector[self.word2index[word_our]])\r\n logger.info(\"Imported word2vec model is verified\")\r\n\r\n def GetWord2Index(self, model):\r\n word2index = {}\r\n word2index[\"UNK\"] = 0\r\n for key, value in model.wv.vocab.items():\r\n word2index[key] = value.index + 1\r\n\r\n if(len(word2index) != self.vocab_size):\r\n logger.error(\"Get word2index error\")\r\n return None\r\n logger.info(\"Got Word2Index\")\r\n return word2index\r\n\r\n def GetIndex2Word(self, model):\r\n index2word = [\"UNK\"] + model.wv.index2word\r\n\r\n if(len(index2word) != self.vocab_size):\r\n logger.error(\"Get index2word error\")\r\n return None\r\n logger.info(\"Got Index2Word\")\r\n return index2word\r\n\r\n def GetWordVector(self, model):\r\n wordvector = np.zeros((self.vocab_size, self.vector_size))\r\n wordvector[0] = np.zeros((self.vector_size))\r\n count = 0\r\n for word in model.wv.index2word:\r\n wordvector[count + 1] = model.wv[word]\r\n count = count + 1\r\n\r\n if(len(wordvector) != self.vocab_size):\r\n logger.error(\"Get WordVector error\")\r\n return None\r\n logger.info(\"Got WordVector\")\r\n return wordvector\r\n\r\n def SentencesIndex(self, sentences, max_document_length):\r\n # indexed_sentences = np.zeros((len(sentences), max_document_length), np.int64)\r\n # for count, sentence in enumerate(sentences):\r\n # sentence_split = sentence.split()\r\n # for index, word in enumerate(sentence_split):\r\n # if word in self.word2index:\r\n # indexed_sentences[count][index] = (self.word2index[word])\r\n # else:\r\n # indexed_sentences[count][index] = 0\r\n indexed_sentences = np.array(\r\n [[self.word2index[word] for word in sentence.split() if word in self.word2index ] for sentence in sentences]\r\n )\r\n logger.info(\"{} Sentences have been indexed\".format(len(indexed_sentences)))\r\n indexed_sentences = np.array([x[:max_document_length - 1] + [0] * max(max_document_length - len(x), 1) for x in indexed_sentences])\r\n return indexed_sentences\r\n \r\nif __name__ == '__main__':\r\n model = Word2Vec.load(modelfile)\r\n word2vec_helpers = Word2VecHelper()\r\n","sub_path":"rnn_src/word2vec_helpers.py","file_name":"word2vec_helpers.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"451469751","text":"import fileinput\n\ndef cycle(list):\n while True:\n yield from list\n\nseen = set([0])\nfrequency = 0\nchanges = cycle(list(fileinput.input()))\n\nfor line in changes:\n try:\n frequency = frequency + int(line)\n if frequency in seen:\n break\n else:\n seen.add(frequency)\n except ValueError:\n print(\"Invalid number: {}\".format(line))\n\nprint(\"Frequency: {}\".format(frequency))","sub_path":"day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"431627537","text":"group_number = -1\ngroup_id = []\ngroups_data = []\ndata = []\n\ndef get_group_number():\n try:\n print_groups()\n global group_number\n num = int(raw_input(\"Enter the number of the group you would like to analyze: \"))\n if num==10:\n print(\"\")\n menu()\n else:\n group_number = num\n if not ( 0<= group_number <= 9 ) :\n print(\"Not a valid integer\")\n get_group_number()\n except ValueError:\n print(\"\\nNot an integer\")\n get_group_number()\n\ndef get_group_id(groups_data, group_number):\n\n group_id = groups_data['response'][group_number]['id']\n return group_id\n\n\ndef get_group_option():\n try:\n print_group_options()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 9 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_group_option()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_group_option()\n\ndef get_group_option_more():\n try:\n print_group_options_more()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 16 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_group_option_more()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_group_option_more()\n\ndef get_person_option():\n try:\n print_person_options()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 9 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_person_option()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_person_option()\n\ndef get_person_option_more():\n try:\n print_person_options_more()\n choice = int(raw_input(\"Enter the number: \"))\n print(\"\")\n if 1<= choice <= 9 :\n return choice\n else:\n print(\"Not a valid integer\\n\")\n return get_person_option_more()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return get_person_option_more()\n\ndef print_person_options():\n options1=[\n 'Number of messages sent all time',\n 'Total likes given all time',\n 'Total likes received all time',\n 'Average likes received per message all time',\n 'Most popular word of all time',\n 'Most liked message',\n 'More options',\n 'Group Specific Statistics',\n 'Back' ]\n print(\"Which statistic would you like to retreive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\ndef print_person_options_more():\n options1=[\n 'Self likes of all time',\n 'Total likes received all time (with self likes subtracted)',\n 'Total words sent all time',\n 'Number of pictures sent all time',\n 'Number of videos sent all time',\n 'Most liked message - Text all time',\n 'Most liked message - Picture all time',\n 'Most liked message - Video all time',\n 'Back'\n ]\n print(\"More options\")\n print(\"Which statistic would you like to receive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\ndef print_group_options():\n options1=[\n 'Your number of messages sent',\n 'Your total likes given',\n 'Your total likes received',\n 'Your average likes received per message',\n 'Your most popular word',\n 'Your most liked message',\n 'More options',\n 'Person Specific Statistics',\n 'Back'\n ]\n print_group_name()\n print(\"Which statistic would you like to retreive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\ndef print_group_options_more():\n options1=[\n 'Self-likes',\n 'Total likes received (with self likes subtracted)',\n 'Total words sent',\n 'Number of pictures sent',\n 'Number of videos sent',\n 'Most liked message - Text',\n 'Most liked message - Picture',\n 'Most liked message - Video',\n 'Number of likes received from each member of group',\n 'Percent of each member\\'s total likes that went to a particular member',\n 'Number of times you liked the same post as another member',\n 'Most \"popular\" person',\n 'Least \"popular\" person',\n 'What time of day is the groupme most active',\n 'Group\\'s most popular word',\n 'Back'\n ]\n print(\"More options for \" + data['response'][group_number]['name'])\n print(\"Which statistic would you like to retreive?\")\n for i in range(len(options1)):\n print(str(i+1)+\". \"+\"\\'\"+options1[i]+\"\\'\")\n\"\"\" get_group_number retrieves the group number. It uses recursion to prompt user\nto input until a valid input is given.\n\"\"\"\ndef print_person_or_group():\n print(\"Which type of statistic would you like to retrieve?\")\n print(\"1 - Group Specific Statistics\")\n print(\"2 - Person Specific Statistics\")\n\n#function that displays groups and retrieves group data\n#Prints all of a user's groupme groups\ndef print_groups():\n\n if len(data['response']) == 0:\n print(\"You are not part of any groups.\")\n return\n print(\"Here are your ten most recent groups:\")\n for i in range(len(data['response'])):\n group = data['response'][i]['name']\n print(str(i)+\". \"+\"\\'\"+group+\"\\'\")\n print(\"10. Back\")\n global groups_data\n groups_data = data\n\ndef get_person():\n\n choice = get_person_option()\n if choice==1:\n #Number of messages sent all time\n donothing=0\n elif choice==2:\n #Total likes given all time\n donothing=0\n elif choice==3:\n #Total likes received all time\n donothing=0\n elif choice==4:\n #Average likes received per message all time\n donothing=0\n elif choice==5:\n #Most popular word of all time\n donothing=0\n elif choice==6:\n #Most liked message\n donothing=0\n elif choice==7:\n #More options\n get_person_more()\n elif choice==8:\n #Group Specific Statistics\n get_groups()\n elif choice==9:\n #Back to menu\n menu()\n\ndef get_groups():\n choice = get_group_option()\n if choice==1:\n #Your number of messages sent\n donothing=0\n elif choice==2:\n #Your total likes given\n donothing=0\n elif choice==3:\n #Your total likes received\n donothing=0\n elif choice==4:\n #Your average likes received per message\n donothing=0\n elif choice==5:\n #Your most popular word\n donothing=0\n elif choice==6:\n #MYour most liked message\n donothing=0\n elif choice==7:\n #More options\n get_groups_more()\n elif choice==8:\n #Person Specific Statistics\n get_person()\n elif choice==9:\n #Back to menu\n group()\n\ndef group():\n choose_which_group()\n get_groups()\n\ndef choose_which_group():\n get_group_number()\n group_id = get_group_id(groups_data, group_number)\n\ndef get_person_more():\n\n choice = get_person_option_more()\n if choice==1:\n #Self likes of all time\n donothing=0\n elif choice==2:\n #Total likes received all time (with self likes subtracted)\n donothing=0\n elif choice==3:\n #Total words sent all time\n donothing=0\n elif choice==4:\n #Number of pictures sent all time\n donothing=0\n elif choice==5:\n #Number of videos sent all time\n donothing=0\n elif choice==6:\n #Most liked message - Text all time\n donothing=0\n elif choice==7:\n #Most liked message - Pic all time\n donothing=0\n elif choice==8:\n #Most liked message - Video all time\n donothing=0\n elif choice==9:\n #Back to previous options\n get_person()\n\ndef print_group_name():\n print(\"\\n\"+data['response'][group_number]['name'])\n\ndef get_groups_more():\n choice = get_group_option_more()\n if choice==1:\n #Self-likes\n donothing=0\n elif choice==2:\n #Total likes received (with self likes subtracted)\n donothing=0\n elif choice==3:\n #Total words sent\n donothing=0\n elif choice==4:\n #Number of pictures sent\n donothing=0\n elif choice==5:\n #Number of videos sent\n donothing=0\n elif choice==6:\n #Most liked message - Text\n donothing=0\n elif choice==7:\n #Most liked message - Pic\n get_groups_more()\n elif choice==8:\n #Most liked message - Video\n get_person()\n elif choice==9:\n #Number of likes received from each member of group\n donothing=0\n elif choice==10:\n #Percent of each member\\'s total likes that went to a particular member\n donothing=0\n elif choice==11:\n #Number of times you liked the same post as another member\n donothing=0\n elif choice==12:\n #Most \"popular\" person\n donothing=0\n elif choice==13:\n #Least \"popular\" person\n donothing=0\n elif choice==14:\n #What time of day is the groupme most active\n donothing=0\n elif choice==15:\n #Group\\'s most popular word\n donothing=0\n elif choice==16:\n #Back\n get_groups()\n\n#function that prompts user to choose between person and group statistics\n#true means they chose group, false means they chose person\ndef chose_group():\n try:\n print_person_or_group()\n choice = int(raw_input(\"Enter the number of the type of statistic: \"))\n if choice==1:\n print(\"\")\n return True\n elif choice==2:\n print(\"\")\n return False\n else:\n print(\"Not a valid integer\\n\")\n return chose_group()\n except ValueError:\n print(\"\\nNot an integer\\n\")\n return chose_group()\n","sub_path":"Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"468057003","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nfrom torch.utils import data\nimport torch.utils.model_zoo as model_zoo\nfrom torchvision import models\n\n\nclass Refine(nn.Module):\n def __init__(self, inplanes, planes, scale_factor=2):\n super(Refine, self).__init__()\n self.convFS1 = nn.Conv2d(inplanes, planes, kernel_size=3, padding=1)\n self.convFS2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.convFS3 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.convMM1 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.convMM2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)\n self.scale_factor = scale_factor\n\n def forward(self, f, pm):\n s = self.convFS1(f)\n sr = self.convFS2(F.relu(s))\n sr = self.convFS3(F.relu(sr))\n s = s + sr\n \n m = s + F.upsample(pm, scale_factor=self.scale_factor, mode='bilinear')\n\n mr = self.convMM1(F.relu(m))\n mr = self.convMM2(F.relu(mr))\n m = m + mr\n return m","sub_path":"RefinementLayers.py","file_name":"RefinementLayers.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"252980726","text":"from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\nBase = declarative_base()\n\n\nclass Person(Base):\n __tablename__ = 'person'\n id = Column(Integer, primary_key=True, unique=True)\n name = Column(String(250), nullable=False)\n screen_name = Column(String(250), nullable=False)\n description = Column(String(250), nullable=False)\n location = Column(String(250), nullable=False)\n url = Column(String(250))\n\n followers_count = Column(Integer, default=0)\n statuses_count = Column(Integer, default=0)\n friends_count = Column(Integer, default=0)\n\n def GetFields():\n f = ('id', 'screen_name', 'name', 'description', 'location',\n 'url', 'followers_count', 'statuses_count', 'friends_count')\n return f\n\n\nclass Status(Base):\n __tablename__ = 'status'\n id = Column(String(250), primary_key=True, unique=True)\n text = Column(String(250), nullable=False)\n created_at = Column(DateTime, nullable=False)\n retweet_count = Column(Integer, default=0)\n retweeted = Column(Boolean, default=False)\n person_id = Column(Integer, ForeignKey('person.id'))\n person = relationship(Person)\n\nengine = create_engine('sqlite:///twittet_app.sqlite')\n# engine = create_engine('postgresql://scott:tiger@localhost/mydatabase')\n# engine = create_engine('postgresql://power_user:$poweruserpassword@ec2-52-32-217-129.us-west-2.compute.amazonaws.com:5432/tweet_db')\n\n\nBase.metadata.create_all(engine)\n","sub_path":"declaration.py","file_name":"declaration.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"99297283","text":"import numpy as np\nfrom scipy.spatial import Voronoi\nimport matplotlib.pyplot as plt\nimport os\nimport math\nimport pandas as pd\nimport matplotlib as mpl\nfrom NucliatorsCount import NucleatorsCounter\n# import TimeResolutionInspection\n\n\nclass NucleationProbabilityAndSPI:\n # todo: refactor to recieve input as variables XY and not file paths.\n def __init__(self, XY, die_times, treatment, time_frame, n_scramble=1000,\n draw=True, dist_threshold_nucliators_detection=200):\n self.mean_time_death = None\n self.nucliators_num = None\n self.time_frame = time_frame\n self.treatment_type = treatment\n self.n_scramble = n_scramble\n self.n_instances = len(die_times)\n self.die_times = die_times\n self.num_blobs = [x for x in range(int(max(self.die_times))+1)]\n self.experiment_time = len(self.num_blobs)\n self.XY = XY\n self.scrambles = self.create_scramble(self.XY, n=n_scramble)\n self.neighbors_difference_death_times = self.get_neighbors_difference_death_times()\n self.original_difference_death_times = self.neighbors_difference_death_times[0]\n self.scramble_signficance_95 = None\n self.scramble_signficance_98 = None\n self.scramble_mean_time_death = None\n self.propagation_index = -1\n self.statistic_score = self.assess_mean()\n self.death_perc_by_time = self.calc_death_perc()\n self.neighbors_stats = []\n self.difference_from_leader = []\n self.get_distance_time_from_leader()\n self.neighbors_list = []\n self.neighbors_list2 = []\n self.neighbors_list3 = []\n self.get_neighbors()\n self.who_is_leader = None\n self.cells_to_leader = None\n self.death_wave = None\n self.identify_leader()\n self.draw() if draw else None\n self.dataframe = None\n self.dist_threshold_nucliators_detection = dist_threshold_nucliators_detection\n self.nucliators_counter = NucleatorsCounter(self.XY, self.die_times, self.neighbors_list, self.dist_threshold_nucliators_detection)\n self.nucliators = None\n self.get_nucliators_num_and_proba()\n self.propagation_index = ((self.scramble_signficance_95 - self.mean_time_death) / self.scramble_signficance_95)\n # self.create_dataframe()\n\n def get_spi_nucleators(self):\n return {'spi': self.propagation_index, 'p_nuc': self.nucliation_proba}\n\n def get_nucliators_num_and_proba(self):\n \"\"\"\n if any of the Voronoy neighbors died before a cell, it is not a nucliator.\n :return:\n \"\"\"\n XY = self.XY\n TIMES = self.die_times\n # CHEN'S IMPLEMENTATION\n # nucliators = np.array([True for i in range(len(TIMES))])\n # leaders = np.array([-1 for i in range(len(TIMES))])\n # cells_idx_sorted_by_times = np.arange(0, len(TIMES), 1)\n # for cell_idx in cells_idx_sorted_by_times:\n # # nucliators[cell_idx] = True\n # cell_death = TIMES[cell_idx]\n # neighbors_prior_death = [True for i in range(len(self.neighbors_list[cell_idx]))]\n # for neighbor_idx in self.neighbors_list[cell_idx]:\n # # if nucliators[cell_idx] == True:\n # # break\n # neighbor_death = TIMES[neighbor_idx]\n # if cell_death > neighbor_death:# and leaders[cell_idx] == -1:\n # nucliators[cell_idx] = False\n # # leaders[cell_idx] = cell_idx\n # elif cell_death == neighbor_death and not nucliators[neighbor_idx]:\n # nucliators[cell_idx] = False\n # leaders[cell_idx] = cell_idx\n # else:\n # nucliators[cell_idx] = True\n # # if leaders[neighbor_idx] != -1:\n # # leaders[cell_idx] = leaders[neighbor_idx]\n #\n # self.nucliators = nucliators\n # self.nucliators_num = nucliators.sum()\n # self.nucliation_proba = self.nucliators_num / len(XY)\n\n # MY IMPLEMENTATION\n self.nucliators = self.nucliators_counter.calc_nucliators()\n self.nucliators_num = self.nucliators.sum()\n self.nucliation_proba = self.nucliators_num / len(self.XY)\n\n def create_dataframe(self):\n instances = []\n x_array = []\n y_array = []\n time_from_leader = []\n distance_from_leader = []\n first_neighbor_distance = []\n second_neighbor_distance = []\n third_neighbor_distance = []\n first_neighbor_time = []\n second_neighbor_time = []\n third_neighbor_time = []\n death_perc = []\n neighbors_number = []\n dead_neighbors_number = []\n has_1_dead_neighbors = []\n has_2_dead_neighbors = []\n has_3_dead_neighbors = []\n has_4_dead_neighbors = []\n has_5_dead_neighbors = []\n has_6_dead_neighbors = []\n has_7_dead_neighbors = []\n has_8_dead_neighbors = []\n has_9_dead_neighbors = []\n has_10_dead_neighbors = []\n # cell_line = []\n # treatment = []\n # signal_analyzed = []\n file_name = []\n neighbors_distance_from_leader = []\n neighbors_stats = self.get_neighbors_stats(self.neighbors_list)\n second_neighbors_num = []\n avg_distance_from_neighbors = []\n for i in range(self.n_instances):\n instances.append(i)\n file_name.append(self.file_name)\n # cell_line.append(self.cell_line)\n # treatment.append(self.treatment)\n x_array.append(self.XY[i][0])\n y_array.append(self.XY[i][1])\n # signal_analyzed.append(self.signal_analyzed)\n second_neighbors_num.append(len(self.neighbors_list2[i]))\n time_from_leader.append(self.difference_from_leader[i][0])\n distance_from_leader.append(self.difference_from_leader[i][1])\n neighbors_distance_from_leader.append(4)\n n = 0\n d = 0\n dis = 0\n for x in neighbors_stats[i]:\n n += 1\n dis += x[2]\n if x[1] >= 0:\n d += 1\n if d == 1:\n first_neighbor_distance.append(x[2])\n first_neighbor_time.append(x[1])\n elif d == 2:\n second_neighbor_distance.append(x[2])\n second_neighbor_time.append(x[1])\n elif d == 3:\n third_neighbor_distance.append(x[2])\n third_neighbor_time.append(x[1])\n n = 1 if n == 0 else n\n death_perc.append(d/n)\n avg_distance_from_neighbors.append(dis / n)\n neighbors_number.append(n)\n dead_neighbors_number.append(d)\n has_2_dead_neighbors.append(1 if d > 1 else 0)\n has_3_dead_neighbors.append(1 if d > 2 else 0)\n has_4_dead_neighbors.append(1 if d > 3 else 0)\n has_5_dead_neighbors.append(1 if d > 4 else 0)\n has_6_dead_neighbors.append(1 if d > 5 else 0)\n has_7_dead_neighbors.append(1 if d > 6 else 0)\n has_8_dead_neighbors.append(1 if d > 7 else 0)\n has_9_dead_neighbors.append(1 if d > 8 else 0)\n has_10_dead_neighbors.append(1 if d > 9 else 0)\n has_1_dead_neighbors.append(1 if d > 0 else 0)\n if d < 3:\n if d <= 2:\n third_neighbor_distance.append(None)\n third_neighbor_time.append(None)\n if d <= 1:\n second_neighbor_distance.append(None)\n second_neighbor_time.append(None)\n if d == 0:\n first_neighbor_distance.append(None)\n first_neighbor_time.append(None)\n for x in self.neighbors_list3[0]:\n neighbors_distance_from_leader[x] = 3\n for x in self.neighbors_list2[0]:\n neighbors_distance_from_leader[x] = 2\n for x in self.neighbors_list[0]:\n neighbors_distance_from_leader[x] = 1\n neighbors_distance_from_leader[0] = 0\n self.get_distance_from_local_leader(dead_neighbors_number)\n feature_table = pd.DataFrame(\n {'id': instances,\n 'file_name': file_name,\n # 'cell_line': cell_line,\n # 'treatment': treatment,\n # 'signal_analyzed': signal_analyzed,\n 'x_loc': x_array,\n 'y_loc': y_array,\n 'die_time': self.die_times,\n 'die_time_real': [x * self.time_frame for x in self.die_times],\n 'cell_leader': self.who_is_leader,\n 'distance_from_leader': distance_from_leader,\n 'is_nucliator': list(self.nucliators),\n 'time_from_leader': time_from_leader,\n 'death_perc': death_perc,\n 'first_neighbor_distance': first_neighbor_distance,\n 'first_neighbor_time': first_neighbor_time,\n 'second_neighbor_distance': second_neighbor_distance,\n 'second_neighbor_time': second_neighbor_time,\n 'third_neighbor_distance': third_neighbor_distance,\n 'third_neighbor_time': third_neighbor_time,\n # 'total_density':self.density,\n # 'point_density':self.density_points,\n 'neighbors_distance_from_leader': neighbors_distance_from_leader,\n 'has_1_dead_neighbors': has_1_dead_neighbors,\n 'has_2_dead_neighbors': has_2_dead_neighbors,\n 'has_3_dead_neighbors': has_3_dead_neighbors,\n 'has_4_dead_neighbors': has_4_dead_neighbors,\n 'has_5_dead_neighbors': has_5_dead_neighbors,\n 'has_6_dead_neighbors': has_6_dead_neighbors,\n 'has_7_dead_neighbors': has_7_dead_neighbors,\n 'has_8_dead_neighbors': has_8_dead_neighbors,\n 'has_9_dead_neighbors': has_9_dead_neighbors,\n 'has_10_dead_neighbors': has_10_dead_neighbors,\n 'neighbors_number': neighbors_number,\n 'second_neighbors_num': second_neighbors_num,\n 'avg_distance_from_neighbors': avg_distance_from_neighbors,\n 'dead_neighbors_number': dead_neighbors_number\n })\n\n # location = self.data_path + \"/File_{}.csv\".format(self.file_name)\n # feature_table.to_csv(location)\n self.dataframe = feature_table\n self.propagation_index = ((self.scramble_signficance_95 - self.mean_time_death) / self.scramble_signficance_95)\n # print(\"SPI: {}\".format(propagation_index))\n\n def create_scramble(self, xy, n=1000):\n scrambles = []\n for i in range(n):\n temp_copy = xy.copy()\n np.random.shuffle(temp_copy)\n scrambles.append(temp_copy)\n return scrambles\n\n def get_neighbors_difference_death_times(self):\n times = []\n times.append(self.get_time_from_neighbors(self.die_times, self.XY))\n for i in range(self.n_scramble):\n times.append(self.get_time_from_neighbors(self.die_times, self.scrambles[i]))\n return times\n\n def get_time_from_neighbors(self, times, points):\n vor = Voronoi(points)\n neighbors = vor.ridge_points\n t = []\n for i in range(len(neighbors)):\n t.append(abs(times[neighbors[i][0]] - times[neighbors[i][1]]))\n return t\n\n def get_neighbors(self):\n vor = Voronoi(self.XY)\n neighbors = vor.ridge_points\n leaders = []\n for i in range(self.n_instances):\n self.neighbors_list.append([])\n self.neighbors_list2.append([])\n self.neighbors_list3.append([])\n for x in neighbors:\n self.neighbors_list[x[0]].append(x[1])\n self.neighbors_list[x[1]].append(x[0])\n for i in range(self.n_instances):\n for j in self.neighbors_list[i]:\n self.neighbors_list2[i] = list(set(self.neighbors_list2[i]+self.neighbors_list[j]))\n for i in range(self.n_instances):\n for j in self.neighbors_list2[i]:\n self.neighbors_list3[i] = list(set(self.neighbors_list3[i]+self.neighbors_list2[j]))\n\n def get_distance_from_local_leader(self, neighbors_death):\n leaders = []\n for i in range(self.n_instances):\n if neighbors_death[i] == 0:\n leaders.append(i)\n closest_leader = []\n distance_from_leader = []\n time_from_leader = []\n for i in range(self.n_instances):\n min_distance = math.sqrt(((self.XY[i][0]-self.XY[0][0])**2)+((self.XY[i][1]-self.XY[0][1])**2))\n min_point = 0\n for j in range(len(leaders)):\n new_distance = math.sqrt(((self.XY[i][0]-self.XY[j][0])**2)+((self.XY[i][1]-self.XY[j][1])**2))\n if new_distance < min_distance:\n min_distance = new_distance\n min_point = j\n closest_leader.append(min_point)\n distance_from_leader.append(min_distance)\n time_from_leader.append(self.die_times[i] - self.die_times[min_point])\n\n def identify_leader(self):\n who_is_leader = [-1]*self.n_instances\n for i in range(self.n_instances):\n temp = []\n for k in self.neighbors_list[i]:\n # if one of the neighbors of cell i is known to be a leader,\n # cell i defines it as its leader (first round nothing happens)\n temp.append(who_is_leader[k]) if who_is_leader[k] > -1 else None\n # if no leader was found for cell i is it's own leader else,\n # the leader for the most of the cell's neighbors is the cell's leader\n who_is_leader[i] = i if len(temp) == 0 else max(set(temp), key=temp.count)\n # calculating the distance of each cell from it's neighbors.\n neighbors_distance = [-1]*self.n_instances\n for i in range(self.n_instances):\n # if the cell is its own leader the distance is 0.\n neighbors_distance[i] = 0 if i == who_is_leader[i] else -1\n for j in range(self.n_instances):\n # for each cell j\n stop_sign = 0\n for i in range(self.n_instances):\n # if distance from neighbor i wasn't calculated so far\n if neighbors_distance[i] == -1:\n for k in self.neighbors_list[i]:\n # each of cell's i neighbors, if the distance from neighbor k was measured,\n # use it plus 1 (bc its a neighbor\n if neighbors_distance[k] > -1:\n neighbors_distance[i] = neighbors_distance[k]+1\n break\n else:\n # if neighbor k has no measured distance yet,\n # increment in 1 nad continue to the next neighbor k of neighbor i\n stop_sign += 1\n # if all neighbors (i) of cell j had all of its neighbors (k) distance measurement,\n # there is nothing to calculate, stop.\n if stop_sign == 0:\n break\n self.who_is_leader = who_is_leader\n self.death_wave = neighbors_distance\n self.nucliators_num = len(set(who_is_leader))\n\n def get_distance_time_from_leader(self):\n for i in range(self.n_instances):\n time = self.die_times[i] - self.die_times[0]\n distance = math.sqrt(((self.XY[i][0]-self.XY[0][0])**2)+((self.XY[i][1]-self.XY[0][1])**2))\n a = (time, distance)\n self.difference_from_leader.append(a)\n\n def get_neighbors_stats(self, neighbors_list):\n neighbors_stats_temp = []\n for i in range(self.n_instances):\n neighbors_stats_temp.append([])\n for j in neighbors_list[i]:\n time = self.die_times[i] - self.die_times[j]\n distance = math.sqrt(((self.XY[i][0]-self.XY[j][0])**2)+((self.XY[i][1]-self.XY[j][1])**2))\n a = (j, time, distance)\n neighbors_stats_temp[i].append(a)\n neighbors_stats = []\n for local_list in neighbors_stats_temp:\n neighbors_stats.append(sorted(local_list, key=lambda x: x[2]))\n return neighbors_stats\n\n def assess_mean(self):\n better_mean = 0\n time_death_means = []\n real_mean_time_death = self.calc_mean(self.neighbors_difference_death_times[0])\n self.mean_time_death = real_mean_time_death * self.time_frame\n for i in range(self.n_scramble):\n temp_mean_time_death = self.calc_mean(self.neighbors_difference_death_times[i + 1])\n time_death_means.append(temp_mean_time_death)\n if temp_mean_time_death > real_mean_time_death:\n better_mean += 1\n time_death_means.sort()\n self.scramble_signficance_95 = time_death_means[int(self.n_scramble * 5 / 100)] * self.time_frame\n self.scramble_signficance_98 = time_death_means[int(self.n_scramble * 2 / 100)] * self.time_frame\n self.scramble_mean_time_death = (sum(time_death_means) / len(time_death_means)) * self.time_frame\n return better_mean / self.n_scramble\n\n def calc_mean(self, l):\n return sum(l) / float(len(l))\n\n def draw(self):\n bins = np.linspace(0, 20, 20)\n histogram_scramble = []\n for z in range(len(self.num_blobs)):\n histogram_scramble.append(0)\n for z in range(len(self.neighbors_difference_death_times[0])):\n for i in range(self.n_scramble):\n j = i + 1\n histogram_scramble[int(self.neighbors_difference_death_times[j][z])] += 1\n avg_scramble_time = []\n for z in range(len(histogram_scramble)):\n histogram_scramble[z] /= self.n_scramble\n n = round(histogram_scramble[z])\n for i in range(n):\n avg_scramble_time.append(z)\n plt.hist(self.neighbors_difference_death_times[0], bins, alpha=0.5, label='Origin')\n plt.hist(avg_scramble_time, bins, alpha=0.5, label=\"Scramble\")\n plt.legend(loc='upper right')\n # location = self.pic_path + \"/histogram_{}.png\".format(self.file_name)\n # plt.savefig(location)\n plt.clf()\n plt.plot(self.death_perc_by_time)\n plt.ylabel('Death Perc')\n plt.xlabel('Time of Death')\n # location = self.pic_path + \"/death_time_{}.png\".format(self.file_name)\n # plt.savefig(location)\n plt.clf()\n self.draw_time_scatter()\n self.draw_wave_scatter()\n\n def calc_death_perc(self):\n death_by_time = [0] * len(self.num_blobs)\n for i in range(self.n_instances):\n death_by_time[int(self.die_times[i])] += 1\n death_by_time_cum = np.cumsum(death_by_time)\n return [x / self.n_instances for x in death_by_time_cum]\n\n def draw_time_scatter(self):\n fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n cmap = plt.get_cmap('jet', len(self.die_times) + 1)\n cmaplist = [cmap(i) for i in range(cmap.N)]\n cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)\n bounds = np.linspace(0, self.experiment_time, self.experiment_time + 1)\n norm = mpl.colors.BoundaryNorm(bounds, cmap.N)\n scat = ax.scatter(self.XY[:, 0], self.XY[:, 1], c=self.die_times, cmap=cmap, norm=norm)\n # scat = ax.scatter(self.listX, self.listY, c=self.die_times, cmap=cmap)\n cb = plt.colorbar(scat, spacing='proportional', ticks=bounds)\n cb.set_label('Custom cbar')\n ax.set_title('Death Time Scatter')\n # location = self.pic_path + \"/death_time_scatter_{}.png\".format(self.file_name)\n # plt.savefig(location)\n plt.clf()\n\n def draw_wave_scatter(self):\n n = max(self.death_wave)\n fig, ax = plt.subplots(1, 1, figsize=(10, 10))\n cmap = plt.cm.jet\n cmaplist = [cmap(i) for i in range(cmap.N)]\n cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)\n bounds = np.linspace(0, n, n + 1)\n norm = mpl.colors.BoundaryNorm(bounds, cmap.N)\n scat = ax.scatter(self.XY[:, 0], self.XY[:, 1], c=self.death_wave, cmap=cmap, norm=norm)\n cb = plt.colorbar(scat, spacing='proportional', ticks=bounds)\n cb.set_label('Custom cbar')\n ax.set_title('Death Wave Scatter')\n location = self.pic_path + \"/death_wave_scatter_{}.png\".format(self.file_name)\n plt.savefig(location)\n plt.clf()\n\n# if __name__ == '__main__':\n# main_exps_fn = '/Users/yishaiazabary/Desktop/University/Thesis/CellDeathThesis/Code/Ferroptosis/ExperimentsXYT_CSVFiles'\n# exp_fn = '20160820_10A_FB_xy11.csv'\n# # exp_fn = '20171008_MCF7_H2O2_xy2.csv'\n# details_file_path = '/Users/yishaiazabary/Desktop/University/Thesis/CellDeathThesis/Code/Ferroptosis/ExperimentsXYT_CSVFiles/File details.csv'\n# full_file_path = os.sep.join([main_exps_fn, exp_fn])\n# exp_data_frame = TimeResolutionInspection.get_exp_data(full_file_path, details_file_path)\n# exp_temp_res = exp_data_frame['temporal_res']\n# exp_xy = exp_data_frame['XY']\n# exp_die_times = exp_data_frame['die_times']\n# exp_treatment = exp_data_frame['treatment']\n# nuc_p_spi = NucleationProbabilityAndSPI(XY=exp_xy,\n# die_times=exp_die_times,\n# time_frame=exp_temp_res,\n# treatment=exp_treatment,\n# n_scramble=1000,\n# draw=False,\n# dist_threshold_nucliators_detection=200)\n# print(nuc_p_spi.get_spi_nucleators())","sub_path":"NucleationProbabilityAndSPI.py","file_name":"NucleationProbabilityAndSPI.py","file_ext":"py","file_size_in_byte":21835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"47058296","text":"# -*- coding: utf-8 -*-\n__title__ = 'Copy View Parameters to Sheet'\n__doc__ = \"\"\"This allows sheet fields for drawing numbering \nto be updated with values from the placed viewport\n\nParameters include:\n\t\"Sub-Discipline\",\n\t\"Uniclass Ss - Group\",\n\t\"Uniclass Ss - Sub group\",\n\t\"Uniclass Ss - Section\",\n\t\"Uniclass Ss - Object\",\n\t\"Role Code\",\n\t\"Discipline Code\",\n\t\"View Description\"\n\n\n\n\n\n\"\"\"\n\n__helpurl__ = \"\"\n\nimport clr\nimport os\nimport os.path as op\nimport pickle as pl\n\nimport sys, os\nimport subprocess\nimport time\n\nimport rpw\nfrom rpw import doc, uidoc, DB, UI\n\nfrom System.Collections.Generic import List\nfrom Autodesk.Revit.DB import *\n\nimport sys, os\n\nfrom System import Array\n\nclr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')\nfrom Microsoft.Office.Interop import Excel\n\n\n\nimport sys, os\n## Add Path to MF Functions folder \t\n\nsys.path.append(os.path.realpath(__file__).split(\"MFTools.extension\")[0] + \"MFTools.extension\\MF_functions\")\n\t\nfrom MF_HeaderStuff import *\n\nfrom MF_SelectStuff import MF_SelectOptions\n\n\n\n\nallSheets = FilteredElementCollector(doc).OfClass(ViewSheet).ToElements()\n\n\n\n#select multiple\nselected = []\nreturn_options = SelectFromCheckBoxes.show(\n\t\t\tsorted([SheetOption(x) for x in allSheets],\n\t\t\t\t key=lambda x: x.number),\n\t\t\ttitle=\"Select Sheets\",\n\t\t\tbutton_name=\"Select Sheets\",\n\t\t\twidth=800)\nif return_options:\n\t\tselected = [x.unwrap() for x in return_options if x.state]\n\n\nsheetList = list(selected)\n\nfields = [\n\n\t\n\t\"Sub-Discipline\",\n\t\"Uniclass Ss - Group\",\n\t\"Uniclass Ss - Sub group\",\n\t\"Uniclass Ss - Section\",\n\t\"Uniclass Ss - Object\",\n\t\"Role Code\",\n\t\"Discipline Code\",\n\t\"View Description\",\n\t\"Zone Description\",\n\t\"MF_Work_section\"\n\n]\n\n#selected_fields = MF_SelectOptions(doc, \"Select Fields to Update\", fields)\n\nfrom mf_views_sheets import copy_view_parameters_to_sheet\n\ntr = Transaction(doc, __title__)\ntr.Start()\n\n\n\n\n\n'''\t\t\nops = ['option1', 'option2', 'option3', 'option4']\nswitches = ['switch1', 'switch2']\ncfgs = {'option1': { 'background': '0xFF55FF'}}\nrops, rswitches = forms.CommandSwitchWindow(\n\t\t\t\t\t\t\t\t\t\tops,\n\t\t\t\t\t\t\t\t\t\tswitches=switches,\n\t\t\t\t\t\t\t\t\t\tmessage='Select Option',\n\t\t\t\t\t\t\t\t\t\tconfig=cfgs\n\t\t\t\t\t\t\t\t\t\t)\t\t\n'''\t\t\nrename_sheet_option\t= False\n\nfor s in sheetList:\n\t\n\t\n\t\t\n\tif s.GetAllViewports():\n\t\t# get viewports placed on sheet\n\t\tviewports = s.GetAllViewports()\n\t\t\n\t\t\n\t\t\n\t\tfor vp in viewports:\n\t\t\tvPort = doc.GetElement(vp)\n\t\t\tview = doc.GetElement(vPort.ViewId)\n\t\t\t\n\t\t\n\t\t\t\n\t\t\tif view.ViewType == ViewType.FloorPlan:\n\t\t\t\tcopy_view_parameters_to_sheet(view, s, rename_sheet_option)\n\t\t\t\t\n\t# try to set the sheet name\n\t\t\n\t\t\n\n\ntr.Commit()\t\t\n\n\n\n","sub_path":"MFTools.extension/MF Project Tools.tab/Sheets.panel/sheets.stack2/Rename Sheets.pulldown/MF Update Sheet Fields from View Fields.pushbutton/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"1424095","text":"import os\nfrom torchtext import data\n\nclass MWP(data.Dataset):\n\n @staticmethod\n def sort_key(ex):\n return len(ex.text)\n\n def __init__(self, data_src, data_tgt, text_field, label_field,\n examples=None, **kwargs):\n \"\"\"Create an MWP dataset instance given a path and fields.\n\n Arguments:\n data_src: Path to source data file.\n data_tgt: Path to target data file.\n text_field: The field that will be used for text data.\n label_field: The field that will be used for label data.\n examples: The examples contain all the data.\n Remaining keyword arguments: Passed to the constructor of\n data.Dataset.\n \"\"\"\n fields = [('text', text_field), ('label', label_field)]\n examples = []\n #print(data_src,data_tgt)\n for i,text in enumerate(data_src):\n eq = data_tgt[i]\n examples += [data.Example.fromlist([text, eq], fields)]\n self.examples = examples\n super(MWP, self).__init__(examples, fields, **kwargs)\n\n @classmethod\n def splits(cls, text_field, label_field, train_src, train_tgt, val_src,\n val_tgt, test_src, test_tgt):\n \"\"\"Create an MWP dataset instance given paths and fields.\n\n Arguments:\n text_field: The field that will be used for text data.\n label_field: The field that will be used for label data.\n train_src: Path to training source data file.\n train_tgt: Path to training target data file.\n val_src: Path to validation source data file.\n val_tgt: Path to validation target data file.\n test_src: Path to test source data file.\n test_tgt: Path to test target data file.\n \"\"\"\n print('Getting training split...')\n train_data = cls(data_src=train_src, data_tgt=train_tgt,\n text_field=text_field, label_field=label_field)\n print('Getting validation split...')\n val_data = cls(data_src=val_src, data_tgt=val_tgt,\n text_field=text_field, label_field=label_field)\n print('Getting test split...')\n test_data = cls(data_src=test_src, data_tgt=val_tgt,\n text_field=text_field, label_field=label_field)\n return tuple(d for d in (train_data, val_data, test_data)\n if d is not None)\n","sub_path":"model/mydatasets.py","file_name":"mydatasets.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"640373730","text":"class Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n height = sorted(zip(list(xrange(len(height))), height), key=lambda x: x[1], reverse=True)\n a = b = height[0][0]\n ans = 0\n for item in height:\n a = max(item[0], a)\n b = min(item[0], b)\n ans = max((a - b) * item[1], ans)\n return ans","sub_path":"container_with_most_water.py","file_name":"container_with_most_water.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"501258479","text":"import numpy as np\n\n\ndef batch(inputs):\n batch_size = len(inputs)\n\n document_sizes = np.array([len(doc) for doc in inputs], dtype=np.int32)\n document_size = document_sizes.max()\n\n sentence_sizes_ = [[len(sent) for sent in doc] for doc in inputs]\n max_sentence_size = max(map(max, sentence_sizes_))\n\n b = np.zeros(shape=[batch_size, document_size, max_sentence_size], dtype=np.int32) # == PAD\n\n sentence_sizes = np.zeros(shape=[batch_size, document_size], dtype=np.int32)\n for i, document in enumerate(inputs):\n for j, sentence in enumerate(document):\n sentence_sizes[i, j] = sentence_sizes_[i][j]\n for k, word in enumerate(sentence):\n b[i, j, k] = word\n\n return b, document_sizes, sentence_sizes\n\ndef load_embedding_vectors_glove(vocabulary, filename, vector_size):\n # load embedding_vectors from the glove\n # initial matrix with random uniform\n embedding_vectors = np.random.uniform(-0.25, 0.25, (len(vocabulary), vector_size))\n f = open(filename)\n for line in f:\n values = line.split()\n word = values[0]\n vector = np.asarray(values[1:], dtype=\"float32\")\n idx = vocabulary.get(word)\n if idx != 0:\n embedding_vectors[idx] = vector\n f.close()\n return embedding_vectors","sub_path":"data_util.py","file_name":"data_util.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"178324638","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nData preprocessing and features extraction\r\n\r\n# features ideas\r\n\r\nfor time:\r\n - keep daytime\r\n - add hour of day = (daytime - daytime(0)) % 24\r\n - add day of year = floor(k * (daytime - daytime(0)) / 24)\r\n\r\nfor each temporal information:\r\n - avg of temporal information for each zone\r\n - difference of temporal information to average\r\n\r\n- station_id [1,2,3,4,5]\r\n- integer (0/1) for calm_day or not\r\n\r\nfor each static features\r\npreprocessing:\r\n\r\n\r\n - fill na with 0\r\n - scale data with MaxAbsScaler to handle sparse data\r\nfeatures:\r\n - a features stat indicate if the |feature| > 0 - is not NaN actually\r\n - the preprocessed value\r\n\"\"\"\r\nimport pandas as pd\r\nfrom sklearn import preprocessing\r\nfrom dataset import cols\r\nimport numpy as np\r\nimport datetime\r\n\r\n\r\ndaytime_0 = 72.0\r\n\r\n\r\ndef fillna_static(df, log=False):\r\n \"\"\" \"\"\"\r\n for col in cols[\"static\"]:\r\n if log:\r\n df[col] = np.log(df.col.fillna(1.0))\r\n else:\r\n df[col] = df[col].fillna(0)\r\n\r\n\r\ndef scale_temporal(train, features_train, dev=None, features_dev=None):\r\n \"\"\" \"\"\"\r\n robust_scaler = preprocessing.RobustScaler()\r\n tmp = pd.DataFrame(\r\n robust_scaler.fit_transform(train[cols[\"temporal\"]]),\r\n columns=[col for col in cols[\"temporal\"]],\r\n index=train.index)\r\n features_train = pd.concat([features_train, tmp], axis=1)\r\n if dev is not None:\r\n tmp = pd.DataFrame(\r\n robust_scaler.transform(dev[cols[\"temporal\"]]),\r\n columns=[col for col in cols[\"temporal\"]],\r\n index=dev.index)\r\n features_dev = pd.concat([features_dev, tmp], axis=1)\r\n return features_train, features_dev\r\n\r\n\r\ndef scale_static(train, features_train, dev=None, features_dev=None, log=False):\r\n \"\"\" \"\"\"\r\n # fill static NaN with 0\r\n fillna_static(train, log)\r\n if dev is not None:\r\n fillna_static(dev, log)\r\n # scale data with MaxAbsScaler to handle sparse static data\r\n max_abs_scaler = preprocessing.MaxAbsScaler()\r\n tmp = pd.DataFrame(\r\n max_abs_scaler.fit_transform(train[cols[\"static\"]]),\r\n columns=[\"%s_sc\" % col for col in cols[\"static\"]],\r\n index=train.index)\r\n features_train = pd.concat([features_train, tmp], axis=1)\r\n if dev is not None:\r\n tmp = pd.DataFrame(\r\n max_abs_scaler.transform(dev[cols[\"static\"]]),\r\n columns=[\"%s_sc\" % col for col in cols[\"static\"]],\r\n index=dev.index)\r\n features_dev = pd.concat([features_dev, tmp], axis=1)\r\n return features_train, features_dev\r\n\r\n\r\ndef binarize_static(train, features_train, dev=None, features_dev=None):\r\n \"\"\" \"\"\"\r\n # binary static features\r\n binarizer = preprocessing.Binarizer()\r\n tmp = pd.DataFrame(\r\n binarizer.fit_transform(train[cols[\"static\"]]),\r\n columns=[\"%s_i\" % col for col in cols[\"static\"]],\r\n index=train.index)\r\n features_train = pd.concat([features_train, tmp], axis=1)\r\n if dev is not None:\r\n tmp = pd.DataFrame(\r\n binarizer.fit_transform(dev[cols[\"static\"]]),\r\n columns=[\"%s_i\" % col for col in cols[\"static\"]],\r\n index=dev.index)\r\n features_dev = pd.concat([features_dev, tmp], axis=1)\r\n return features_train, features_dev\r\n\r\n\r\ndef delta_temporal_station_zone(train, features_train, dev=None,\r\n features_dev=None):\r\n \"\"\" \"\"\"\r\n # add difference of average in zone and value in station\r\n for col in cols[\"temporal\"]:\r\n features_train[\"delta_%s\" % col] = train[\"%s_avg\" % col] - train[col]\r\n if dev is not None:\r\n features_dev[\"delta_%s\" % col] = dev[\"%s_avg\" % col] - dev[col]\r\n # scaled it\r\n scaler = preprocessing.StandardScaler()\r\n features_train[[\"delta_%s\" % col for col in cols[\"temporal\"]]] = \\\r\n scaler.fit_transform(\r\n features_train[[\"delta_%s\" % col for col in cols[\"temporal\"]]])\r\n if dev is not None:\r\n features_dev[[\"delta_%s\" % col for col in cols[\"temporal\"]]] = \\\r\n scaler.transform(\r\n features_dev[[\"delta_%s\" % col for col in cols[\"temporal\"]]])\r\n return features_train, features_dev\r\n\r\n\r\ndef add_temporal_rolling_mean(delta, train, features_train,\r\n dev=None, features_dev=None,\r\n columns=None):\r\n \"\"\" \"\"\"\r\n if columns is None:\r\n columns = cols[\"temporal\"]\r\n # compute rolling mean of step delta\r\n rol_df = train.groupby(\"block\")[columns] \\\r\n .rolling(delta, min_periods=0).mean() \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_mean_%i\" % (col, delta))\r\n for col in columns),\r\n inplace=True)\r\n features_train = features_train.merge(\r\n rol_df, left_index=True, right_index=True, copy=False)\r\n if dev is not None:\r\n rol_df = dev.groupby(\"block\")[columns] \\\r\n .rolling(delta, min_periods=0).mean() \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_mean_%i\" % (col, delta))\r\n for col in columns),\r\n inplace=True)\r\n features_dev = features_dev.merge(\r\n rol_df, left_index=True, right_index=True,\r\n suffixes=(\"\", \"_mean_%i\" % delta))\r\n # scale it\r\n # scaler = preprocessing.RobustScaler()\r\n # features_train[\r\n # [\"%s_mean_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.fit_transform(\r\n # features_train[[\"%s_mean_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n # if dev is not None:\r\n # features_dev[\r\n # [\"%s_mean_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.transform(\r\n # features_dev[[\"%s_mean_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n return features_train, features_dev\r\n\r\n\r\ndef rolling_mean_col(df, delta, cols):\r\n \"\"\" \"\"\"\r\n if isinstance(cols, basestring):\r\n cols = [cols]\r\n # compute rolling mean of step delta\r\n rol_df = df.groupby(\"block\")[cols] \\\r\n .rolling(delta, min_periods=0).mean() \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_mean_%i\" % (col, delta)) for col in cols),\r\n inplace=True)\r\n return rol_df\r\n\r\n\r\ndef add_temporal_rolling_std(delta, train, features_train,\r\n dev=None, features_dev=None):\r\n \"\"\" \"\"\"\r\n # compute rolling mean of step delta\r\n rol_df = train.groupby(\"block\")[cols[\"temporal\"]] \\\r\n .rolling(delta, min_periods=0).std() \\\r\n .fillna(method=\"bfill\") \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_std_%i\" % (col, delta))\r\n for col in cols[\"temporal\"]),\r\n inplace=True)\r\n features_train = features_train.merge(\r\n rol_df, left_index=True, right_index=True, copy=False)\r\n if dev is not None:\r\n rol_df = dev.groupby(\"block\")[cols[\"temporal\"]] \\\r\n .rolling(delta, min_periods=0).std() \\\r\n .fillna(method=\"bfill\") \\\r\n .reset_index(0, drop=True) \\\r\n .sort_index()\r\n rol_df.rename(\r\n columns=dict((col, \"%s_std_%i\" % (col, delta))\r\n for col in cols[\"temporal\"]),\r\n inplace=True)\r\n features_dev = features_dev.merge(\r\n rol_df, left_index=True, right_index=True,\r\n suffixes=(\"\", \"_std_%i\" % delta))\r\n # scale it\r\n # scaler = preprocessing.RobustScaler()\r\n # features_train[\r\n # [\"%s_std_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.fit_transform(\r\n # features_train[[\"%s_std_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n # if dev is not None:\r\n # features_dev[\r\n # [\"%s_std_%i\" % (col, delta) for col in cols[\"temporal\"]]\r\n # ] = scaler.transform(\r\n # features_dev[[\"%s_std_%i\" % (col, delta)\r\n # for col in cols[\"temporal\"]]])\r\n return features_train, features_dev\r\n\r\n\r\ndef add_temporal_shift(config, features_train, features_dev=None):\r\n \"\"\" \"\"\"\r\n for col, delays in config.items():\r\n for delay in delays:\r\n features_train[\"%s_shift_%i\" % (col, delay)] = \\\r\n features_train[col].shift(delay).fillna(method=\"bfill\")\r\n if features_dev is not None:\r\n features_dev[\"%s_shift_%i\" % (col, delay)] = \\\r\n features_dev[col].shift(delay).fillna(method=\"bfill\")\r\n #\r\n return features_train, features_dev\r\n\r\n\r\ndef add_temporal_decomposition(freq, train, features_train, dev=None,\r\n features_dev=None, scale=False):\r\n \"\"\" \"\"\"\r\n temporal_train_dec = decompose_temporal(freq, train)\r\n # scale it\r\n if scale:\r\n scaler = preprocessing.StandardScaler(with_mean=True)\r\n temporal_train_dec[temporal_train_dec.columns] = \\\r\n scaler.fit_transform(temporal_train_dec)\r\n # merge\r\n features_train = features_train.merge(\r\n temporal_train_dec, left_index=True, right_index=True)\r\n if dev is not None:\r\n temporal_dev_dec = decompose_temporal(freq, dev)\r\n # scale it\r\n if scale:\r\n temporal_dev_dec[temporal_dev_dec.columns] = \\\r\n scaler.transform(temporal_dev_dec)\r\n # merge\r\n features_dev = features_dev.merge(\r\n temporal_dev_dec, left_index=True, right_index=True)\r\n return features_train, features_dev\r\n\r\n\r\ndef decompose_temporal(freq, train, log=True):\r\n \"\"\" \"\"\"\r\n import statsmodels.api as sm\r\n hour = datetime.timedelta(hours=1)\r\n d = datetime.datetime(2014, 1, 1, 0, 0)\r\n decompose = []\r\n for k, g in train.groupby(\"block\"):\r\n #\r\n g[\"daytime\"] = g[\"daytime\"].map(lambda x: d + int(x) * hour)\r\n tmp = g.set_index(pd.DatetimeIndex(g[\"daytime\"]))\r\n acc = g[[\"daytime\"]]\r\n for col in cols[\"temporal\"]:\r\n dec = sm.tsa.seasonal_decompose(tmp[[col]], freq=freq)\r\n res = concat_decomposition(dec)\r\n res = res.fillna(0.)\r\n acc = acc.merge(res, left_index=False, right_index=True,\r\n left_on=\"daytime\")\r\n decompose.append(acc)\r\n return pd.concat(decompose, axis=0).drop(\"daytime\", axis=1).sort_index()\r\n\r\n\r\ndef concat_decomposition(dec):\r\n \"\"\" \"\"\"\r\n to_merge = [\r\n dec.seasonal.rename(\r\n index=str,\r\n columns={dec.seasonal.columns[0]: \"%s_seasonal\" % dec.seasonal.columns[0]}),\r\n dec.trend.rename(\r\n index=str,\r\n columns={dec.trend.columns[0]: \"%s_trend\" % dec.trend.columns[0]}),\r\n dec.resid.rename(\r\n index=str,\r\n columns={dec.resid.columns[0]: \"%s_resid\" % dec.resid.columns[0]}),\r\n ]\r\n res = pd.concat(to_merge, axis=1)\r\n # cast index to datetime\r\n res = res.set_index(pd.DatetimeIndex(res.index))\r\n return res\r\n\r\n\r\ndef to_log(df):\r\n \"\"\" \"\"\"\r\n res = df.copy()\r\n for col in [\"temperature\", \"pressure\"]:\r\n res[col] = np.log(273.0 + df[col])\r\n return res\r\n\r\n\r\ndef hours_day(df):\r\n \"\"\" \"\"\"\r\n return df.daytime.map(lambda x: (x - daytime_0) % 24)\r\n # df[\"day_of_year\"] = df.hour_of_day.map(lambda x: x % 24)\r\n\r\n\r\ndef day_of_week(df):\r\n \"\"\" \"\"\"\r\n return df.daytime.map(lambda x: ((x - daytime_0) // 24) % 7)\r\n\r\n\r\ndef normalize_df(df):\r\n \"\"\" \"\"\"\r\n return pd.DataFrame(preprocessing.normalize(df), columns=df.columns,\r\n index=df.index)\r\n\r\n\r\ndef drop_cols(df, cols):\r\n \"\"\" \"\"\"\r\n return df[[col for col in df.columns if col not in cols]]\r\n\r\n\r\ndef make_features(train, dev=None, scale_temp=True,\r\n rolling_mean=True, deltas_mean=[], roll_mean_conf={},\r\n rolling_std=True, deltas_std=[],\r\n shift_config={}, temp_dec_freq=0,\r\n binary_static=False,\r\n pollutant=False,\r\n remove_temporal=False, log=False):\r\n \"\"\" \"\"\"\r\n general_col = [\"zone_id\", \"is_calmday\", \"daytime\"]\r\n f_train = train[general_col]\r\n if pollutant:\r\n encoder = preprocessing.LabelEncoder()\r\n f_train[\"pollutant\"] = encoder.fit_transform(train[\"pollutant\"])\r\n # hour of day & day of week\r\n f_train[\"hour_of_day\"] = hours_day(train)\r\n f_train[\"day_of_week\"] = day_of_week(train)\r\n # day of week\r\n if dev is not None:\r\n f_dev = dev[general_col]\r\n if pollutant:\r\n f_dev[\"pollutant\"] = encoder.fit_transform(dev[\"pollutant\"])\r\n # hour of day & day of week\r\n f_dev[\"hour_of_day\"] = hours_day(dev)\r\n f_dev[\"day_of_week\"] = day_of_week(dev)\r\n else:\r\n f_dev = None\r\n # to log for temperature and pressure\r\n if log:\r\n train = to_log(train)\r\n if dev is not None:\r\n dev = to_log(dev)\r\n # scale temporal features with robust scaling\r\n if scale_temp:\r\n f_train, f_dev = scale_temporal(train, f_train, dev, f_dev)\r\n else:\r\n f_train[cols[\"temporal\"]] = train[cols[\"temporal\"]]\r\n if dev is not None:\r\n f_dev[cols[\"temporal\"]] = dev[cols[\"temporal\"]]\r\n # scale data with MaxAbsScaler to handle sparse static data\r\n f_train, f_dev = scale_static(train, f_train, dev, f_dev, log=log)\r\n # binary static features\r\n if binary_static:\r\n f_train, f_dev = binarize_static(train, f_train, dev, f_dev)\r\n # Rolling mean of step delta\r\n if rolling_mean:\r\n if roll_mean_conf:\r\n for delta, columns in roll_mean_conf.items():\r\n f_train, f_dev = add_temporal_rolling_mean(\r\n delta, train, f_train, dev, f_dev, columns)\r\n else:\r\n for delta in deltas_mean:\r\n f_train, f_dev = add_temporal_rolling_mean(\r\n delta, train, f_train, dev, f_dev)\r\n # Rolling Std of step deltas_std\r\n if rolling_std:\r\n for delta in deltas_std:\r\n f_train, f_dev = add_temporal_rolling_std(\r\n delta, train, f_train, dev, f_dev)\r\n # temporal shift\r\n if shift_config:\r\n f_train, f_dev = add_temporal_shift(shift_config, f_train, f_dev)\r\n # temporal decomposition\r\n if temp_dec_freq:\r\n f_train, f_dev = add_temporal_decomposition(\r\n temp_dec_freq, train, f_train, dev, f_dev)\r\n if remove_temporal:\r\n f_train = drop_cols(f_train, cols[\"temporal\"])\r\n if dev is not None:\r\n f_dev = drop_cols(f_dev, cols[\"temporal\"])\r\n # drop daytime col\r\n if \"daytime\" in f_train:\r\n f_train.drop(\"daytime\", axis=1, inplace=True)\r\n if dev is not None:\r\n if \"daytime\" in f_dev:\r\n f_dev.drop(\"daytime\", axis=1, inplace=True)\r\n #\r\n if dev is not None:\r\n return f_train, f_dev\r\n else:\r\n return f_train\r\n\r\n\r\ndef build_sequences(df, seq_length, pad=False, pad_value=0., norm=True):\r\n \"\"\" \"\"\"\r\n seqs = []\r\n ids = np.empty(shape=[0])\r\n for _, g in df.groupby(\"block\"):\r\n g[\"ID\"] = g.index\r\n g = g.set_index(\"daytime\").sort_index().drop(\"block\", axis=1)\r\n array = g.drop(\"ID\", axis=1).values\r\n ids.append(g.ID)\r\n np.concatenate((ids, g.ID.as_matrix()), axis=0)\r\n # L2 normalize\r\n if norm:\r\n array = preprocessing.normalize(array)\r\n # seqs = []\r\n for k in range(1, seq_length + 1):\r\n seqs.append(array[:k])\r\n for k in range(seq_length, array.shape[0]):\r\n seqs.append(array[k - seq_length:k])\r\n if pad:\r\n from keras.preprocessing.sequence import pad_sequences\r\n seqs = pad_sequences(seqs, maxlen=seq_length, dtype='float32',\r\n padding='pre', truncating='pre', value=pad_value)\r\n return seqs, ids\r\n\r\n\r\ndef make_seqential_features(train, dev=None, seq_length=12, normalize=False,\r\n temp_dec_freq=0, pollutant=False,\r\n remove_temporal=False, log=False):\r\n \"\"\" \"\"\"\r\n # make standard features\r\n f_train, f_dev = make_features(train, dev=dev, scale_temporal=True,\r\n temp_dec_freq=temp_dec_freq,\r\n pollutant=pollutant,\r\n remove_temporal=remove_temporal, log=log)\r\n # sequantialize\r\n # add block column\r\n f_train[\"block\"] = train[\"block\"]\r\n train_seqs, train_ids = build_sequences(f_train, seq_length=seq_length,\r\n pad=True, norm=normalize)\r\n if dev is not None:\r\n f_dev[\"block\"] = dev[\"block\"]\r\n dev_seqs, dev_ids = build_sequences(f_dev, seq_length=seq_length,\r\n pad=True, norm=normalize)\r\n # return\r\n if dev is not None:\r\n return train_seqs, train_ids, dev_seqs, dev_ids\r\n else:\r\n return train_seqs, train_ids\r\n\r\n\r\ndef make_hybrid_features(train, dev=None, seq_length=12, normalize=False,\r\n temp_dec_freq=0, pollutant=False,\r\n remove_temporal=False, log=False):\r\n \"\"\" \"\"\"\r\n columns = [\"daytime\", \"zone_id\", \"hour_of_day\", \"day_of_week\",\r\n \"is_calmday\", \"block\"]\r\n if temp_dec_freq:\r\n remove_temporal = True\r\n # make standard features\r\n f_train, f_dev = make_features(train, dev=dev, scale_temporal=True,\r\n temp_dec_freq=temp_dec_freq,\r\n pollutant=pollutant,\r\n remove_temporal=remove_temporal, log=log)\r\n\r\n # add block column\r\n f_train[\"block\"] = train[\"block\"]\r\n # temporal features: sequential\r\n temp_cols = [col for col in cols[\"temporal\"]]\r\n f_temp_train = f_train[columns + temp_cols].drop(\"zone_id\", axis=1)\r\n train_temp_seqs, train_ids = build_sequences(\r\n f_temp_train, seq_length=seq_length, pad=True, norm=normalize)\r\n if dev is not None:\r\n f_dev[\"block\"] = dev[\"block\"]\r\n f_temp_dev = f_dev[columns + temp_cols].drop(\"zone_id\", axis=1)\r\n dev_temp_seqs, dev_ids = build_sequences(\r\n f_temp_dev, seq_length=seq_length, pad=True, norm=normalize)\r\n # static features\r\n static_cols = [\"%s_sc\" % col for col in cols[\"static\"]] + [\"zone_id\"]\r\n # add wind sin and cosin\r\n static_cols.extend(\"windbearingcos\", \"windbearingsin\")\r\n train_static_ds = np.empty(shape=[0, len(static_cols)])\r\n gb = f_train.groupby(\"block\")\r\n for k, group in gb:\r\n group = group.set_index(\"daytime\").sort_index()\r\n train_static_ds = np.concatenate(\r\n (train_static_ds, group[static_cols].values), axis=0)\r\n if normalize:\r\n train_static_ds = preprocessing.normalize(train_static_ds)\r\n if dev is not None:\r\n dev_static_ds = np.empty(shape=[0, len(static_cols)])\r\n gb = f_dev.set_index(\"daytime\").groupby(\"block\")\r\n for k, group in gb:\r\n dev_static_ds = np.concatenate(\r\n (dev_static_ds, group[static_cols].values), axis=0)\r\n if normalize:\r\n dev_static_ds = preprocessing.normalize(dev_static_ds)\r\n # return\r\n if dev is not None:\r\n return [train_temp_seqs, train_static_ds, train_ids], [dev_temp_seqs, dev_static_ds, dev_ids]\r\n else:\r\n return [train_temp_seqs, train_static_ds, train_ids]\r\n\r\n\r\ndef get_seq_Y(X, Y, pollutant=None):\r\n \"\"\" \"\"\"\r\n Y_seq = np.empty(shape=[0])\r\n X_u = X[[\"daytime\", \"block\", \"pollutant\"]]\r\n Y_u = Y.merge(X_u, left_index=True, right_index=True, how=\"inner\")\r\n # if no pollutant passed find it\r\n if pollutant is None:\r\n tmp = Y_u.pollutant.unique()\r\n if len(tmp) == 1:\r\n pollutant = tmp[0]\r\n else:\r\n raise ValueError(\r\n \"Many pollutants in df, please set one in pollutant arg\")\r\n gb = Y_u[Y_u[\"pollutant\"] == pollutant].groupby(\"block\")\r\n for k, group in gb:\r\n Y_seq = np.concatenate((Y_seq, group.TARGET.values))\r\n return Y_seq\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n \"\"\" \"\"\"\r\n pass\r\n\r\n\r\n\r\n","sub_path":"features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":20345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"459929353","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"Text viewer widget for use with QAD and Redux.\"\"\"\n\ntry:\n from PyQt5 import QtWidgets, QtGui, QtCore\n from sofia_redux.pipeline.gui.ui import ui_textview\nexcept ImportError:\n HAS_PYQT5 = False\n QtGui = None\n\n # duck type parents to allow class definition\n class QtWidgets:\n class QDialog:\n pass\n\n class ui_textview:\n class Ui_TextWindow:\n pass\nelse:\n HAS_PYQT5 = True\n\n__all__ = ['TextView']\n\n\nclass TextView(QtWidgets.QDialog, ui_textview.Ui_TextWindow):\n \"\"\"\n View, find, and filter text.\n\n All attributes and methods for this class are intended for internal\n use, in response to user actions within a Qt5 application.\n \"\"\"\n def __init__(self, parent=None):\n \"\"\"\n Initialize the text viewer widget.\n\n Parameters\n ----------\n parent : `QWidget`\n Parent widget.\n \"\"\"\n if not HAS_PYQT5: # pragma: no cover\n raise ImportError('PyQt5 package is required for Redux GUI.')\n\n # parent initialization\n QtWidgets.QDialog.__init__(self, parent)\n\n # set up UI from Designer generated file\n self.setupUi(self)\n\n # make sure there's a close button\n self.setWindowFlags(QtCore.Qt.Window\n | QtCore.Qt.WindowMaximizeButtonHint\n | QtCore.Qt.WindowMinimizeButtonHint\n | QtCore.Qt.WindowCloseButtonHint)\n\n # connect buttons\n self.findButton.clicked.connect(self.find)\n self.filterButton.clicked.connect(self.filter)\n self.tableButton.setEnabled(False)\n\n # hide save button: should only appear if text is editable\n self.saveButton.setVisible(False)\n\n # last loaded text\n self.text = None\n self.html = None\n\n def load(self, text):\n \"\"\"\n Load text into the widget.\n\n Parameters\n ----------\n text : list of str\n The text to display.\n \"\"\"\n if text is None:\n text = ''\n if type(text) is not list:\n text = [text]\n\n self.text = text\n\n # format to HTML\n self.html = self.format()\n\n # set text in text window\n self.textEdit.setHtml(self.html)\n self.textEdit.repaint()\n\n def setTitle(self, title):\n \"\"\"Set the window title.\"\"\"\n self.setWindowTitle(title)\n\n def find(self):\n \"\"\"Find a string within the text.\"\"\"\n\n # read text to find\n # whole field will be matched; comma-separated fields not allowed\n find_text = self.findText.text().strip()\n\n cursor = self.textEdit.textCursor()\n if find_text == '':\n # set cursor back to beginning of document\n cursor.movePosition(QtGui.QTextCursor.Start)\n self.textEdit.setTextCursor(cursor)\n else:\n # find next instance\n found = self.textEdit.find(find_text)\n if not found:\n # wrap back to beginning and try one more find\n cursor.movePosition(QtGui.QTextCursor.Start)\n self.textEdit.setTextCursor(cursor)\n self.textEdit.find(find_text)\n self.textEdit.repaint()\n\n def filter(self):\n \"\"\"Filter text to lines containing a specified string.\"\"\"\n\n # read text to filter\n # may be comma-separated substrings\n find_text = self.findText.text().strip()\n\n if find_text == '':\n # clear previous filter / table\n self.textEdit.setHtml(self.html)\n else:\n # allow multiple filter keys\n sep = find_text.split(',')\n\n # split text on lines\n header = self.html.split(' ')\n\n # find substrings in lines\n filtered = []\n for line in header:\n added = False\n\n # keep anchored lines -- filename headers, tags\n if '' in line:\n filtered.append(line)\n else:\n for text in sep:\n if added:\n break\n if text.strip().lower() in line.lower():\n filtered.append(line)\n added = True\n self.textEdit.setHtml(' '.join(filtered))\n\n # repaint required for some versions of Qt/OS\n self.textEdit.repaint()\n\n def format(self):\n \"\"\"\n Format the input text to HTML for display.\n\n Returns\n -------\n str\n HTML-formatted text.\n \"\"\"\n anchor = ' '\n br = ' '\n\n text_str = br.join(self.text)\n html = '' + anchor + br + text_str + br + ' ' + anchor\n\n return html\n","sub_path":"sofia_redux/pipeline/gui/textview.py","file_name":"textview.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"481058330","text":"from django.shortcuts import render\nfrom rest_framework.generics import CreateAPIView, ListAPIView\nfrom .serializers import UserSerializer, PublicUserSerizlizer\nfrom rest_framework import permissions\nfrom django.contrib.auth.models import User\n\nclass UserCreateView(CreateAPIView):\n serializer_class = UserSerializer\n permission_classes = [permissions.AllowAny]\n\n\nclass UserListView(ListAPIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = PublicUserSerizlizer\n\n def get_queryset(self):\n queryset = User.objects.exclude(id=self.request.user.pk)\n\n return queryset\n \nclass UsernameView(ListAPIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = PublicUserSerizlizer\n\n def get_queryset(self):\n return User.objects.filter(id=self.request.user.id)\n ","sub_path":"chat/apps/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"468874931","text":"import numpy as np\nfrom KalmanFilter import KalmanFilter\nfrom scipy.optimize import linear_sum_assignment\nfrom collections import deque\nimport cv2\n\nclass Tracks(object):\n\t\"\"\"docstring for Tracks\"\"\"\n\tdef __init__(self, detection, trackId):\n\t\tsuper(Tracks, self).__init__()\n\t\tself.KF = KalmanFilter()\n\t\tself.KF.predict()\n\t\tself.KF.correct(np.matrix(detection).reshape(2,1))\n\t\tself.trace = deque(maxlen=500)\n\t\tself.nframe = deque(maxlen=500)\n\t\tself.prediction = detection.reshape(1,2)\n\t\tself.trackId = trackId\n\t\tself.skipped_frames = 0\n\n\tdef predict(self,detection):\n\t\tself.prediction = np.array(self.KF.predict()).reshape(1,2)\n\t\tself.KF.correct(np.matrix(detection).reshape(2,1))\n\n\tdef genMainPoints(self, fps = 25):\n\n\t\tmain_points = np.ones(9)*-1\n\t\tmain_points[0] = self.trackId\n\t\tif len(self.trace) == 0:\n\t\t\treturn main_points\n\t\tmain_points[1] = self.nframe[0]/fps\n\t\tif (40 > self.trace[0][0,0]) and (20 < self.trace[0][0,1]):\n\t\t\tmain_points[2] = 0\n\t\t\tmain_points[3] = 1\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0,0] > 40:\n\t\t\t\t\tmain_points[7] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] > 200:\n\t\t\t\t\tmain_points[8] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\telif (340 < self.trace[0][0,0]) and (20 < self.trace[0][0,1]):\n\t\t\tmain_points[2] = 3\n\t\t\tmain_points[3] = 2\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 200:\n\t\t\t\t\tmain_points[7] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 40:\n\t\t\t\t\tmain_points[8] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\telif (340 > self.trace[0][0,0] > 200) and (20 > self.trace[0][0,1]):\n\t\t\tmain_points[2] = 5\n\t\t\tmain_points[3] = 4\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 200:\n\t\t\t\t\tmain_points[7] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\t\tfor i in range(len(self.nframe)):\n\t\t\t\tif self.trace[i][0, 0] < 40:\n\t\t\t\t\tmain_points[8] = self.nframe[i]/fps\n\t\t\t\t\tbreak\n\t\tmain_points[4] = self.nframe[-1]/fps\n\t\tif (40 > self.trace[-1][0,0]) and (20 < self.trace[-1][0,1]):\n\t\t\tmain_points[5] = 1\n\t\t\tmain_points[6] = 0\n\t\telif (340 < self.trace[-1][0,0]) and (20 < self.trace[-1][0,1]):\n\t\t\tmain_points[5] = 2\n\t\t\tmain_points[6] = 3\n\t\telif (340 > self.trace[-1][0,0] > 200) and (20 > self.trace[-1][0,1]):\n\t\t\tmain_points[5] = 4\n\t\t\tmain_points[6] = 5\n\n\t\treturn main_points\n\n\n\n\nclass PeopleTrack(object):\n\t\"\"\"docstring for Tracker\"\"\"\n\tdef __init__(self, dist_threshold, max_frame_skipped, max_trace_length):\n\t\tsuper(PeopleTrack, self).__init__()\n\t\tself.dist_threshold = dist_threshold\n\t\tself.max_frame_skipped = max_frame_skipped\n\t\tself.max_trace_length = max_trace_length\n\n\n\t\t#private\n\t\tself.__trackId = 0\n\t\tself.__tracks = []\n\t\tself.__removed_tracks = []\n\t\tself.__nframes = -1\n\t\tself.__track_colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0),\n\t\t\t\t\t\t(127, 127, 255), (255, 0, 255), (255, 127, 255),\n\t\t\t\t\t\t(127, 0, 255), (127, 0, 127),(127, 10, 255), (0,255, 127)]\n\n\n\tdef update(self, detections):\n\t\t'''This function update the tracker positions and manage them'''\n\n\t\t# Update the current frame\n\t\tself.__nframes += 1\n\t\t# If no detections are passed, them these statements manage it.\n\t\tif detections.size == 0:\n\n\t\t\tfor i in range(len(self.__tracks)):\n\t\t\t\tself.__tracks[i].skipped_frames +=1\n\n\t\t\tdel_tracks = []\n\t\t\tfor i in range(len(self.__tracks)):\n\t\t\t\tif self.__tracks[i].skipped_frames > self.max_frame_skipped:\n\t\t\t\t\tdel_tracks.append(i)\n\n\t\t\tif len(del_tracks) > 0:\n\t\t\t\tfor i in range(len(del_tracks)):\n\t\t\t\t\tself.__removed_tracks.append(self.__tracks[del_tracks[i]])\n\t\t\t\t\tdel self.__tracks[del_tracks[i]]\n\n\t\t\treturn 0\n\n\n\t\tif len(self.__tracks) == 0:\n\t\t\tfor i in range(detections.shape[0]):\n\t\t\t\ttrack = Tracks(detections[i], self.__trackId)\n\t\t\t\tself.__trackId +=1\n\t\t\t\tself.__tracks.append(track)\n\n\t\t# Calculate the distance between detentions and prediction for each track\n\t\tN = len(self.__tracks)\n\t\tM = len(detections)\n\t\tcost = []\n\t\tfor i in range(N):\n\t\t\tdiff = np.linalg.norm(self.__tracks[i].prediction - detections.reshape(-1,2), axis=1)\n\t\t\tcost.append(diff)\n\n\t\tcost = np.array(cost)*0.1\n\t\trow, col = linear_sum_assignment(cost)\n\t\tassignment = [-1]*N\n\t\tfor i in range(len(row)):\n\t\t\tassignment[row[i]] = col[i]\n\n\t\tun_assigned_tracks = []\n\n\t\t# Check if the threshold condition is fulfilled\n\t\tfor i in range(len(assignment)):\n\t\t\tif assignment[i] != -1:\n\t\t\t\tif (cost[i][assignment[i]] > self.dist_threshold):\n\t\t\t\t\tassignment[i] = -1\n\t\t\t\t\tun_assigned_tracks.append(i)\n\t\t\t\t# else:\n\t\t\t\t# \tself.tracks[i].skipped_frames += 1\n\t\t\telse:\n\t\t\t\tself.__tracks[i].skipped_frames +=1\n\n\t\t#Those with no assigments are deleted\n\t\tdel_tracks = []\n\t\tfor i in range(len(self.__tracks)):\n\t\t\tif self.__tracks[i].skipped_frames > self.max_frame_skipped :\n\t\t\t\tdel_tracks.append(i)\n\n\t\tif len(del_tracks) > 0:\n\t\t\tfor i in range(len(del_tracks)):\n\t\t\t\tself.__removed_tracks.append(self.__tracks[del_tracks[i]])\n\t\t\t\tdel self.__tracks[del_tracks[i]]\n\t\t\t\tdel assignment[del_tracks[i]]\n\n\t\tfor i in range(len(detections)):\n\t\t\tif i not in assignment:\n\t\t\t\ttrack = Tracks(detections[i], self.__trackId)\n\t\t\t\tself.__trackId +=1\n\t\t\t\tself.__tracks.append(track)\n\n\n\t\tfor i in range(len(assignment)):\n\t\t\tif(assignment[i] != -1):\n\t\t\t\tself.__tracks[i].skipped_frames = 0\n\t\t\t\tself.__tracks[i].predict(detections[assignment[i]])\n\t\t\tself.__tracks[i].trace.append(self.__tracks[i].prediction)\n\t\t\tself.__tracks[i].nframe.append(self.__nframes)\n\n\tdef drawTracks(self, frame):\n\t\t'''This function allows you tu paint tracks on the frame'''\n\t\tfor j in range(len(self.__tracks)):\n\t\t\tif (len(self.__tracks[j].trace) > 1):\n\t\t\t\tx = int(self.__tracks[j].trace[-1][0, 0])\n\t\t\t\ty = int(self.__tracks[j].trace[-1][0, 1])\n\t\t\t\ttl = (x - 10, y - 10)\n\t\t\t\tbr = (x + 10, y + 10)\n\t\t\t\tcv2.rectangle(frame, tl, br, self.__track_colors[j], 1)\n\t\t\t\tcv2.putText(frame, str(self.__tracks[j].trackId), (x - 10, y - 20), 0, 0.5, self.__track_colors[j], 2)\n\t\t\t\tfor k in range(len(self.__tracks[j].trace)):\n\t\t\t\t\tx = int(self.__tracks[j].trace[k][0, 0])\n\t\t\t\t\ty = int(self.__tracks[j].trace[k][0, 1])\n\t\t\t\t\tcv2.circle(frame, (x, y), 3, self.__track_colors[j], -1)\n\t\t\t\tcv2.circle(frame, (x, y), 6, self.__track_colors[j], -1)\n\n\t\treturn frame\n\n\tdef reportMainPoints(self, rtype = 'all', timelapsemin = 5, fps = 25):\n\t\t'''Generate a report of the main points concerning to each track\n\t\t:param rtype: type of report to be generated. Choose between 'all' or 'best'\n\t\t:type rtype: str\n\t\t:param timelapsemin: minime time distance between first and last frame\n\t\t:type timelapsemin: int\n\t\t:param fps: frames per second\n\t\t:type fps: int\n\t\t'''\n\t\tall_tracks = self.__tracks + self.__removed_tracks\n\t\treport = []\n\t\tfor i in range(len(all_tracks)):\n\t\t\treport.append(all_tracks[i].genMainPoints(fps = fps))\n\n\t\tif rtype == 'all':\n\t\t\treturn np.array(report)\n\t\tif rtype == 'best':\n\t\t\treport_best = []\n\t\t\tfor rp in report:\n\t\t\t\tif (rp[4]-rp[1]) > timelapsemin:\n\t\t\t\t\treport_best.append(rp)\n\t\t\treturn np.array(report_best)\n\n\n\n\n\n\n\t\t\n\n\n\n","sub_path":"PeopleTrack.py","file_name":"PeopleTrack.py","file_ext":"py","file_size_in_byte":6896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"191042774","text":"\"\"\"Implementation of a LinkedList\"\"\"\n\n\nclass LinkedList:\n \"\"\"An implementation of a linked list data structure\"\"\"\n\n def __init__(self):\n self.__size = 0\n self.__head = None\n\n def append(self, item):\n \"\"\"Append element\"\"\"\n\n if self.__size == 0:\n self.__head = Node(item, None)\n else:\n new_node = Node(item, None)\n last_node = self.__head\n\n for i in range(0, self.__size - 1):\n last_node = last_node.pointer\n\n last_node.pointer = new_node\n\n self.__size += 1\n\n def get(self, index):\n \"\"\"Get element given index\"\"\"\n\n node = self.__head\n\n for i in range(0, index):\n node = node.pointer\n\n return node.value\n\n def delete(self, index):\n \"\"\"Delete element given index\"\"\"\n\n if index == 0:\n self.__head = self.__head.pointer\n else:\n last_node = self.__head\n\n for i in range(0, index - 1):\n last_node = last_node.pointer\n\n last_node.pointer = last_node.pointer.pointer\n\n self.__size -= 1\n\n def size(self):\n \"\"\"Get size of array\"\"\"\n\n return self.__size\n\n\nclass Node:\n\n def __init__(self, value, pointer):\n\n self.value = value\n self.pointer = pointer\n","sub_path":"data_structures/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"276111802","text":"\"Write a Program to show whether the entered number is prime or not\"\n\ndef is_prime(number:int) -> bool:\n # Edge Cases\n if number == 1: return False\n \n # loop through all numbers from 2 to number and check remainder\n for i in range(2, number):\n if number % i == 0:\n return False\n return True\n\ndef main():\n __input = int(input(\"Enter number to check: \"))\n if is_prime(__input):\n print(f\"Number {__input} is Prime\")\n else:\n print(f\"Number {__input} is not Prime\")\n \nif __name__ == \"__main__\":\n main()\n\n__OUTPUT__ = \"\"\"\nEnter number to check: 13\nNumber 13 is Prime\n\"\"\"","sub_path":"22_is_prime.py","file_name":"22_is_prime.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"138601506","text":"from thetis import *\r\nimport pyproj\r\nimport numpy as np\r\nimport input_file_paths\r\nimport pandas as pd\r\nfrom modules import utm\r\n\r\n\r\ndef read_tide_gauge_data_file():\r\n tidegauge_file = input_file_paths.tidegauge_file\r\n data = pd.read_csv(tidegauge_file, header=21, sep='\\s+')\r\n data = data.drop(data[(data['Year'] < 1975)].index)\r\n data = data.drop(data[(data['Days'] < 30)].index)\r\n # data = data.loc[data.round(0).sort_values('Year', ascending=False).drop_duplicates(subset=['Lat', 'Lon'], keep='last').sort_index().index]\r\n data.Location = pd.io.parsers.ParserBase({'names': data.Location})._maybe_dedup_names(data.Location)\r\n # print(data.to_string()) # see which detectors are being sorted\r\n return data\r\n\r\n\r\ndef get_detectors(mesh2d):\r\n gauge_data = read_tide_gauge_data_file()\r\n gauge_latlon = gauge_data[['Lat', 'Lon']].values\r\n gauge_names = gauge_data['Location'].values\r\n gauge_xy = []\r\n gauge_locs = []\r\n for loc, (lat, lon) in zip(gauge_names, gauge_latlon):\r\n x, y, zone_num, zone_l = utm.from_latlon(lat, lon)\r\n if zone_num == 30:\r\n gauge_xy.append([x, y])\r\n gauge_locs.append(loc)\r\n gauge_xy = np.array(gauge_xy)\r\n gauge_locs = np.array(gauge_locs)\r\n return select_and_move_detectors(mesh2d, gauge_xy, gauge_locs, maximum_distance=1e2)\r\n\r\n\r\nUTM_ZONE30 = pyproj.Proj(\r\n proj='utm',\r\n zone=30,\r\n datum='WGS84',\r\n units='m',\r\n errcheck=True)\r\n\r\nLL_WGS84 = pyproj.Proj(proj='latlong', datum='WGS84', errcheck=True)\r\n\r\nif __name__ == \"__main__\":\r\n mesh2d = Mesh(input_file_paths.mesh_file)\r\n locations, names = get_detectors(mesh2d)\r\n if mesh2d.comm.rank == 0: # only processor 0\r\n print_output(\"Found detectors: {}\".format(names))\r\n # write out shape-file\r\n import shapely.geometry\r\n import fiona\r\n import fiona.crs\r\n schema = {'geometry': 'Point', 'properties': {'name': 'str'}}\r\n crs = fiona.crs.from_string(UTM_ZONE30.srs)\r\n with fiona.collection(\"mesh_files/detectors.shp\", \"w\", \"ESRI Shapefile\", schema, crs=crs) as output:\r\n for xy, name in zip(locations, names):\r\n point = shapely.geometry.Point(xy[0], xy[1])\r\n output.write({'properties': {'name': name}, 'geometry': shapely.geometry.mapping(point)})\r\n","sub_path":"detectors.py","file_name":"detectors.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"591802880","text":"import argparse\n\n\nclass Parser():\n def __init__(self):\n self.test = False\n self.initialized = False\n\n def initialize(self, parser):\n parser.add_argument('--name', type=str, default='Ludwig', help='Meine Name')\n parser.add_argument('--faction', type=str, default='Nazi', help='Meine Ehre')\n parser.add_argument('--grade', type=int, default=20, help='Nothing Else')\n self.initialized = True\n return parser\n\n def create_parser(self):\n if not self.initialized:\n parser = argparse.ArgumentParser()\n parser = self.initialize(parser)\n return parser\n\n\nif __name__ == '__main__':\n parser = Parser().create_parser()\n opt, _ = parser.parse_known_args()\n print('name = ', opt.name)\n print('faction = ', opt.faction)\n print('grade = ', opt.grade)","sub_path":"Python/argparse/argparse_sample.py","file_name":"argparse_sample.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"498160783","text":"from sys import path\npath.append(\"/mydata/QIK-Videos/APTED/apted\")\npath.append(\"/mydata/QIK-Videos/QIK_Web/util/\")\n\nimport os\nimport threading\nimport json\nimport time\nfrom threading import Thread, Lock\n\nTHREAD_COUNT = 100\nVIDEO_LIST_FILE = 'QIK_Index_Engine_Results_With_Optimized_Times.txt'\nRESULTS_FILE_PREFIX = 'qik_msrvtt_q_testset_d_trainvalset_ted_weighed_ranked_optimized_times'\n\nqueue = []\nlock = Lock()\nthreadLimiter = threading.BoundedSemaphore()\n\n# Producer Thread.\nclass Producer(Thread):\n def run(self):\n global queue\n\n if os.path.exists(VIDEO_LIST_FILE):\n # Iterating over the images mentioned in the file.\n videos = open(VIDEO_LIST_FILE, \"r\")\n for video in videos:\n # Acquiring the lock before adding the to the queue.\n lock.acquire()\n\n # Adding the file to the queue.\n queue.append(os.fsdecode(video.rstrip()))\n\n # Releasing the lock acquired.\n lock.release()\n\n# Consumer Thread.\nclass Consumer(Thread):\n def run(self):\n global queue\n while True:\n if not queue:\n # Nothing in queue, but consumer will try to consume\n continue\n\n # Acquiring the lock before removing from the queue.\n lock.acquire()\n\n # Fetching the files from the queue.\n file = queue.pop(0)\n\n # Releasing the lock acquired.\n lock.release()\n\n # Instantiate a thread with the file name as the thread name.\n process = Process(name=file)\n process.start()\n time.sleep(1)\n\n\nclass Process(threading.Thread):\n def run(self):\n threadLimiter.acquire()\n try:\n self.exec()\n finally:\n threadLimiter.release()\n\n def exec(self):\n # Getting the complete image path\n line = self.getName().split(\"::\")\n\n # Obtaining the video and response\n query = line[0]\n resp = line[1].replace(\"{'\", \"{\\\"\").replace(\"'}\", \"\\\"}\").replace(\", '\", \", \\\"\").replace(\"', \", \"\\\", \").replace(\": '\", \": \\\"\").replace(\"': \", \"\\\": \").replace(\"['\", \"[\\\"\").replace(\"']\", \"\\\"]\")\n\n # Interpreting the response as a json object\n stored_res = json.loads(resp)\n\n # Obtaining the time data\n scene_detect_time = stored_res['sceneDetectTime']\n captioning_time = stored_res[\"captioningTime\"]\n retrieval_time = stored_res[\"dbRetrievalTime\"]\n ranking_time = stored_res[\"rankingTime\"]\n total_time = scene_detect_time + captioning_time + retrieval_time + ranking_time\n\n # Writing results to the file\n with open(RESULTS_FILE_PREFIX + \".csv\", 'a+') as f:\n f.write(query + \",\" + str(scene_detect_time) + \",\" + str(captioning_time) + \",\" + str(retrieval_time) + \",\" + str(ranking_time) + \",\" + str(total_time) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n # Starting the producer process\n Producer().start()\n\n # Starting the consumer process.\n Consumer().start()","sub_path":"QIK-Videos/Evaluate/MSR_VTT/get_time_data_from_json.py","file_name":"get_time_data_from_json.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"315629938","text":"#########################\r\n######## Imports ########\r\n#########################\r\n\r\nimport pandas as pd\r\n\r\nfrom scipy import linalg, mat, dot\r\n\r\nfrom preprocessing import tokenize, stem\r\n\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer \r\n\r\n\r\n#########################\r\n#### Initializisation ###\r\n#########################\r\n\r\nvectorizer = CountVectorizer()\r\n\r\nmetadata = pd.read_csv('allocine_parser_results.csv', sep=';')\r\ndata_titles = metadata['titre']\r\n\r\n\r\n\r\n#########################\r\n######### CODE ##########\r\n#########################\r\n\r\ndef identify_title(filmAsked):\r\n\r\n titles = pd.concat([data_titles, pd.Series([filmAsked])], ignore_index = True)\r\n n = len(titles)\r\n \r\n ''' Step 1 = Preprocessing without StopWords '''\r\n \r\n new_titles = []\r\n \r\n for index, title in titles.iteritems():\r\n new_title = tokenize(title)\r\n for idx, word in enumerate(new_title):\r\n new_title[idx] = stem(word)\r\n new_title = \" \".join(new_title)\r\n new_titles.append(new_title)\r\n \r\n \r\n ''' Step 2 = TF-IDF matrix building '''\r\n \r\n tfidf_vectorizer = TfidfVectorizer(use_idf=True)\r\n tfidf_vectorizer_vectors = tfidf_vectorizer.fit_transform(new_titles)\r\n \r\n tfidf_matrix = pd.DataFrame(columns=tfidf_vectorizer.get_feature_names())\r\n \r\n for i in range(n):\r\n \r\n vector_tfidfvectorizer = tfidf_vectorizer_vectors[i] \r\n row = vector_tfidfvectorizer.T.todense()\r\n \r\n # Place tf-idf values in a pandas data frame \r\n dfNew = pd.DataFrame(row, index=tfidf_vectorizer.get_feature_names())\r\n tfidf_matrix = tfidf_matrix.append(dfNew.T, ignore_index=True)\r\n \r\n \r\n ''' Step 3 = Cos-similarity computation '''\r\n \r\n cos_similarity = []\r\n \r\n tfidf_list = tfidf_matrix.values.tolist()\r\n \r\n a = mat(tfidf_list[-1])\r\n \r\n for i in range(n-1):\r\n \r\n b = mat(tfidf_list[i])\r\n c = (dot(a,b.T)/linalg.norm(a)/linalg.norm(b)).item()\r\n \r\n cos_similarity.append(c)\r\n \r\n \r\n similarities = pd.Series(cos_similarity)\r\n similarities = similarities.sort_values()\r\n indexes = similarities[-3:].index.tolist()\r\n indexes.reverse()\r\n \r\n expectedFilms = []\r\n \r\n for index in indexes:\r\n expectedFilms.append(titles[index])\r\n \r\n return expectedFilms, indexes\r\n\r\n\r\ndef read_result(index, nameClass):\r\n \r\n return metadata[nameClass][index]\r\n\r\n \r\n\r\n","sub_path":"Retrieve_model__TFIDF/title_detection.py","file_name":"title_detection.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"584150148","text":"from services import *\n\nSID_DETECTED = False\n\nclass member:\n def __init__(self, one):\n self.one = one\n def getDeclaration(self, addExtern = True):\n return ''\n def getSID(self):\n return ''\n def getTypedef(self):\n return ''\n def isStatic(self):\n return False\n def getAll(self):\n return self.one\n\nclass func(member):\n def __init__(self, one):\n super().__init__(one)\n self.__parse(self.one)\n\n def __parse(self, text):\n #find body\n bodyStart = text.find('{')\n bodyEnd = findEnd(text, '\\n', (findEnd(text, '\\n}', bodyStart)))\n self.body = text[bodyStart:bodyEnd]\n #find parameters\n parametersStart = text.rfind('(', 0, bodyStart)\n parametersEnd = rfindEnd(text, ')', bodyStart)\n self.parameters = text[parametersStart:parametersEnd]\n #find funcName\n funcNameStart = rfindEnd(text, ' ', parametersStart)\n funcNameEnd = parametersStart\n self.funcName = text[funcNameStart:funcNameEnd]\n self.fatFuncName = camel2SnakeSingle(self.funcName)\n #find funcType\n funcTypeStart = rfindEnd(text, '\\n', funcNameStart)\n funcTypeEnd = funcNameStart\n self.funcType = text[funcTypeStart:funcTypeEnd]\n #find hat\n hatStart = 0\n hatEnd = funcTypeStart\n self.hat = text[hatStart:hatEnd]\n #find SID\n self.sid = self.__detectSid(self.hat)\n #find short description\n self.desc = self.__makeShortDescription(self.hat)\n\n def __makeShortDescription(self, text):\n descStart = findEnd(self.hat, '@Description')\n descEnd = self.hat.find('//--', descStart)\n if (descStart < descEnd) and (descStart != -1) and (descEnd != -1):\n desc = ('// ' + self.hat[descStart:descEnd])\n else:\n desc = '// TODO\\n'\n return deleteDoubles(desc)\n\n def __detectSid(self, text):\n global SID_DETECTED\n sidPosition = text.find('SID')\n if sidPosition != -1:\n SID_DETECTED = True\n sidStart = text.find('0x', sidPosition)\n if (sidStart != -1) and (sidStart - sidPosition < 10):\n sidEnd = sidStart + 4\n return text[sidStart:sidEnd]\n else:\n sidEnd = sidPosition + 10\n return text[sidPosition:sidEnd]\n else:\n return ''\n\n def getSID(self):\n if self.sid != '':\n result = ('#define {0:50} ({1}U)\\n'.format(self.fatFuncName + '_SID', self.sid))\n else:\n result = ''\n return result\n\n def getTypedef(self):\n fType = self.funcType\n fType = fType.replace('static', '')\n fType = fType.replace('const', '')\n fName = self.funcName + 'Ptr_t'\n t = deleteDoubles('typedef {0} (*{1})'.format(fType, fName))\n head = self.funcName + self.funcType\n diffNames = max(len(t) - len(head), len(head) - len(t))\n joiner = ('\\n' + ' ' * diffNames)\n return (t + joiner.join(self.parameters.split('\\n'))+ ';\\n')\n\n def getDeclaration(self, addExtern = True):\n head = self.funcType + self.funcName\n if self.isStatic():\n declaration = (self.desc + head + self.parameters + ';\\n')\n else:\n if addExtern:\n add = 'extern '\n else:\n add = ''\n localParams = self.parameters.replace('\\n', '\\n' + ' ' * len(add))\n declaration = (self.desc + add + head + localParams + ';\\n')\n return declaration\n\n def isStatic(self):\n return ('static' in self.funcType)\n\nclass preprocessor(member):\n def getDeclaration(self, addExtern = True):\n return self.one\n\ndef getAllSIDs(functions):\n text = ''\n if (shortDialog('I\\'ve detected SIDs in comments.\\nDo you want to export them?')):\n text = '\\n// SIDs:\\n'\n for f in functions:\n text += f.getSID()\n return text\n\n@benchmark\ndef parsingFunctions(f):\n text = getCleanText(f)\n f_Array = []\n fCounter = 0\n #find first comment\n startPosition = text.rfind('\\n\\n//', 0, text.find('\\n{'))\n while(1):\n #find preprocessor first\n preStart = text.find('#', startPosition)\n fbodyStart = text.find('\\n{', startPosition)\n #add preprocessor if he first\n if (preStart != -1) and ((preStart < fbodyStart) or (fbodyStart == -1)):\n preEnd = findEnd(text, '\\n', preStart)\n f_Array.append(preprocessor(text[preStart:preEnd]))\n startPosition = preEnd\n #add function\n elif (fbodyStart != -1):\n fCounter += 1\n fbodyEnd = findEnd(text, '\\n}', fbodyStart)\n fbodyEnd = findEnd(text, '\\n', fbodyEnd)\n fhatStart = text.find('//', startPosition)\n if fhatStart != -1:\n f_Array.append(func(text[fhatStart:fbodyEnd]))\n startPosition = fbodyEnd\n #if end of members\n else:\n break\n printLog('Total functions detected: ' + str(fCounter))\n return f_Array\n\ndef prepareToExport(func):\n def wrapped():\n inFile = openFile()\n exFile = createFile('export.c')\n functions = parsingFunctions(inFile)\n\n func(functions, exFile)\n\n inFile.close()\n exFile.close()\n\n return wrapped\n\ndef addSpace(text, space = '\\n'):\n addSpace.added = getattr(addSpace, 'added', True)\n\n if (text.find('#if') != -1):\n text = space + text\n addSpace.added = True\n elif text.find('#endif') != -1:\n addSpace.added = False\n elif addSpace.added:\n addSpace.added = False\n else:\n text = space + text\n addSpace.added = False\n return text\n\n@prepareToExport\ndef exportDeclarations(functions, exFile):\n addGlobal = shortDialog('Export global functions?')\n if addGlobal:\n addEx = shortDialog('Add extern to global?')\n else: \n addEx = False\n addStatic = shortDialog('Export static functions?')\n\n for f in functions:\n if (f.isStatic() and addStatic) or (not f.isStatic() and addGlobal) or \\\n (type(f) is type(preprocessor)):\n exFile.write(addSpace(f.getDeclaration(addExtern = addEx)))\n \n if (SID_DETECTED):\n exFile.write(getAllSIDs(functions))\n printLog('Declarations exported in ' + exFile.name)\n\n@prepareToExport\ndef exportStaticPointers(functions, exFile):\n if shortDialog('Array name \\'StaticFs\\'?'):\n arrayName = 'StaticFs'\n else:\n arrayName = input('Enter your array\\'s name: \\n')\n #typedef void-void\n exFile.write('\\n\\n\\n// Put this into your \\'Module.h\\'\\n')\n exFile.write('typedef void(*ptrToFunct_t)(void);\\n')\n #array generation\n exFile.write('\\n\\n\\n// Put this into bottom of your \\'Module.c\\'\\n')\n exFile.write(SPLITTER + '// Array of (void)(*)(void) pointers to static functions\\n' + SPLITTER)\n exFile.write('ptrToFunct_t {0}[] =\\n{1}\\n'.format(arrayName, '{'))\n counter = 0\n for f in functions:\n if f.isStatic():\n exFile.write(' [{0}] = (ptrToFunct_t){1},\\n'.format(counter, f.funcName))\n counter += 1\n exFile.write('};\\n\\n')\n #declaration of the array\n exFile.write('\\n\\n\\n// Put this into your \\'Module_Getters.h\\'\\n')\n exFile.write(SPLITTER + '// Declarations of global (public) variables\\n' + SPLITTER)\n exFile.write('\\nextern ptrToFunct_t {0}[];\\n'.format(arrayName))\n #typedefs\n exFile.write('\\n\\n\\n// Put this into your \\'Module_Tests.c\\'\\n')\n exFile.write(SPLITTER + '// Declarations of global (public) data types\\n' + SPLITTER)\n for f in functions:\n if f.isStatic():\n exFile.write(f.getTypedef() + '\\n')\n #definitions of static vars\n exFile.write(SPLITTER + '// Definitions of static global (private) variables\\n' + SPLITTER)\n for f in functions:\n if f.isStatic():\n exFile.write('{0:40}{1};\\n'.format('static '+ f.funcName + 'Ptr_t', f.funcName))\n\n exFile.write('\\n\\n\\n// Put this into your \\'TestsInitFunction()\\'\\n')\n counter = 0\n for f in functions:\n if f.isStatic():\n exFile.write('{0:40} = ({1}){2}[{3}];\\n'\\\n .format(f.funcName, f.funcName + 'Ptr_t', arrayName, counter))\n counter += 1\n\n@prepareToExport\ndef exportAllFunctions(functions, exFile):\n for f in functions:\n exFile.write(addSpace(f.getAll(), '\\n\\n\\n'))\n printLog('All functions were exported in ' + exFile.name)","sub_path":"functionsGen.py","file_name":"functionsGen.py","file_ext":"py","file_size_in_byte":8506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"499173735","text":"hid = \"4103261995xxxx3197\"\n\nverify_id = str(hid)[-1]\nleft = hid[0:10]\nright = hid[14:18]\n\nmonth = range(1, 13)\nday = range(1, 32)\n\nfakes = []\nfor mon in month:\n for d in day:\n mm = ''\n dd = ''\n if mon < 10:\n mm = '0' + str(mon)\n else:\n mm = str(mon)\n\n if d < 10:\n dd = '0' + str(d)\n else:\n dd = str(d)\n\n mid = mm + dd\n fake = left + mid + right\n fakes.append(fake)\n\narr = []\nfor i in range(0, 17):\n a = (1 << 17 - i) % 11\n arr.append(a)\n\nfor idcard in fakes:\n\n a = str(idcard)[0:-1]\n\n check_sum = 0\n for (inx, z) in enumerate(a):\n num = int(z)\n check_sum += num * arr[inx]\n\n check_digit = (12 - check_sum % 11) % 11\n\n if check_digit == int(verify_id):\n print(idcard[10:14])\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"629056041","text":"import numpy as np\nfrom scipy.integrate import ode\n#from matplotlib import pyplot as plt\n#from matplotlib import animation\n#import pickle\n\nclass flow(object):\n def __init__(self, nx=64, ny=64, lx=1.0e6, ly=2.0e6,\n beta=6.0e-10, kappa=10.0, w=4.0e-6, forcing_mode=(6,9),\n method='dopri5', dt=2*3600,\n initial_amp=1.2e5):\n x = np.linspace(-np.pi, np.pi, nx, endpoint=False)\n y = np.linspace(-np.pi, np.pi, ny, endpoint=False)\n self.xx, self.yy = np.meshgrid(x,y, indexing='ij')\n \n kx = np.fft.fftfreq(nx, lx/nx)\n ky = np.fft.rfftfreq(ny, ly/ny)\n self.kkx, self.kky = np.meshgrid(kx,ky, indexing='ij')\n \n self.ksq = self.kkx**2 + self.kky**2\n self.ksq[0,0] += 1.0e-15\n self.kmax = np.min(np.max(kx), np.max(ky))\n self.kxmax = np.max(kx)\n self.kymax = np.max(ky)\n \n self.nx = nx\n self.ny = ny\n self.lx = lx\n self.ly = ly\n self.beta = beta\n self.kappa = kappa\n self.w = w\n \n self.forcing_mode = forcing_mode\n\n self.psihat = np.zeros_like(self.ksq, dtype=complex)\n\n # should we do random noise instead for initial condition?\n# self.psihat[2,4] = nx*ny*4\n# self.psihat[4,2] = nx*ny\n# self.psi = np.fft.irfft2(self.psihat)\n \n# self.qhat = -self.psihat*self.ksq\n# self.q = np.fft.irfft2(self.qhat)\n\n self.qhat = self.forcing(0.0) * initial_amp\n self.q = np.fft.irfft2(self.qhat)\n self.psihat = self.get_psihat_from_qhat(self.qhat)\n self.psi = np.fft.irfft2(self.psihat)\n\n\n self.integrator = ode(self.rhs).set_integrator(method)\n self.results = [ self.qhat ]\n self.dt = dt\n self.t = 0.0\n\n \n def integrate(self, tf):\n \n if tf < self.t + self.dt:\n print(\"won't integrate backward in time from %f to %f\" %(self.t,tf))\n return\n \n y0 = self.munge(self.qhat)\n self.integrator.set_initial_value(y0, self.t)\n while self.integrator.successful() and self.integrator.t < tf:\n self.integrator.integrate(self.integrator.t + self.dt)\n self.results.append(self.unmunge(self.integrator.y))\n \n self.qhat = self.unmunge(self.integrator.y)\n self.psihat = self.get_psihat_from_qhat(self.qhat)\n self.psi = np.fft.irfft2(self.psihat)\n self.q = np.fft.irfft2(self.qhat)\n self.t = self.integrator.t\n \n return\n \n# def plot_psi(self):\n# return plt.contour(self.xx, self.yy, self.psi)\n \n# def plot_q(self):\n# return plt.contour(self.xx, self.yy, self.q)\n \n \n def get_psihat_from_qhat(self, qhat):\n \"\"\"What it says on the tin. \n \"\"\"\n \n psihat = qhat/self.ksq\n return psihat\n \n def waveterm(self, psihat):\n \"\"\"Compute the beta wave term.\n \n Assume that we start and end in Fourier space.\n \"\"\"\n return self.beta*psihat*self.kkx*(0.0+1.0j)\n \n def dissipation(self, qhat):\n \"\"\"Dissipation term, all in Fourier space.\"\"\"\n \n return self.kappa*qhat*self.ksq\n \n def forcing(self, t):\n \"\"\"Forcing term goes here.\n \n This ought to be random phases into a k-space anulus, but I'll use something simple for now.\n \"\"\"\n fzero = 1.0e-4\n thick = 1.0e3\n famp = self.w * fzero/thick\n\n phases = np.random.uniform(-np.pi, np.pi, size=self.ksq.shape)\n \n forcing = np.zeros_like(self.ksq, dtype=complex)\n forcing[np.abs(self.ksq - self.kmax**2/9) < 3e-11] = famp\n forcing *= (np.cos(phases) + np.sin(phases)*(0.0+1.0j))\n \n return forcing\n \n def nlterm(self, qhat, psihat):\n \"\"\"Compute the jacobian determinant.\"\"\"\n \n psihat_x = psihat*self.kkx*(0.0+1.0j)\n psihat_y = psihat*self.kky*(0.0+1.0j)\n qhat_x = qhat*self.kkx*(0.0+1.0j)\n qhat_y = qhat*self.kky*(0.0+1.0j)\n \n psi_x = np.fft.irfft2(psihat_x)\n psi_y = np.fft.irfft2(psihat_y)\n q_x = np.fft.irfft2(qhat_x)\n q_y = np.fft.irfft2(qhat_y)\n \n jac = psi_x*q_y - psi_y*q_x\n \n jachat = np.fft.rfft2(jac)\n \n # dealias\n jachat[self.kkx > 2/3 * self.kxmax] = 0.0\n jachat[self.kky > 2/3 * self.kymax] = 0.0\n \n return jachat\n \n def rhs(self, arg1, arg2):\n \"\"\"The time derivative, ready for the integrator.\"\"\"\n \n # scipy.ode and scipy.odeint use opposite call signatures\n # so we have to figure out which of the arguments is a float\n # and which is an array\n \n if type(arg1) == type(0.0):\n t = arg1\n q_reshaped = arg2\n else:\n t = arg2\n q_reshaped = arg1\n \n qhat = self.unmunge(q_reshaped)\n \n psihat = self.get_psihat_from_qhat(qhat)\n nlterm = self.nlterm(qhat, psihat)\n waveterm = self.waveterm(psihat)\n dissipation = self.dissipation(qhat)\n forcing = self.forcing(t)\n \n return self.munge(forcing - dissipation + waveterm + nlterm)\n \n def calc_energy(self, psihat):\n uhat = psihat*self.kkx*(0.0+1.0j)\n vhat = psihat*self.kky*(0.0+1.0j)\n \n u = np.fft.irfft2(uhat)\n v = np.fft.irfft2(vhat)\n \n efield = u**2 + v**2\n return np.sum(efield)\n \n def calc_enstrophy(self, qhat):\n q = np.fft.irfft2(qhat)\n return np.sum(q**2)\n \n def munge(self, qhat):\n \"\"\"format a complex k-space field for odeint\"\"\"\n \n r = qhat.real\n i = qhat.imag\n z = np.array([r,i])\n return z.reshape(-1)\n \n def unmunge(self, munged):\n \"\"\"Return the 1d real sequence to its 2d complex state\"\"\"\n \n z = munged.reshape((2,self.nx,int(self.ny/2+1)))\n r = z[0]\n i = z[1]\n return r + (0+1.0j)*i\n \n \n# def animate_results(self, filename, stride=1):\n# fig = plt.figure(figsize=(10,10))\n# ax = plt.axes()\n#\n# plt.xlabel(r'x')\n# plt.ylabel(r'y')\n#\n# def animate(i):\n# qhat = self.results[int(i*stride)]\n# psihat = self.get_psihat_from_qhat(qhat)\n# z = np.fft.irfft2(psihat)\n# ax.clear()\n# cont = plt.contour(self.xx, self.yy, z)\n# return cont\n#\n# anim = animation.FuncAnimation(fig, animate, frames=len(self.results)//stride, blit=False)\n# mywriter = animation.FFMpegWriter()\n# anim.save(filename, bitrate=10000)\n","sub_path":"layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":6740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"33808053","text":"from flask import Flask,render_template,redirect\nfrom flask_pymongo import PyMongo\nimport scrape_mars\n\n#create an instance for Flask\napp=Flask(__name__)\n\n#set up Mongo connection \napp.config[\"MONGO_URI\"]=\"mongodb://localhost:27017/mars_app\"\nmongo= PyMongo(app)\n\n@app.route(\"/\")\ndef index():\n\n mars_dic=mongo.db.mars_dic.find_one()\n return render_template(\"index.html\",mars=mars_dic)\n\n\n@app.route(\"/scrape\")\ndef scrape():\n\n mars_dic=mongo.db.mars_dic\n mars_data=scrape_mars.scrape()\n mars_dic.update({},mars_data,upsert=True)\n return redirect(\"/\",code=302)\n\nif __name__==\"__main__\":\n app.run(debug=True)\n ","sub_path":"Mission_to_Mars/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"143763292","text":"class Heap:\r\n def __init__(self):\r\n self.distv=[]\r\n self.vertic=[]\r\n self.length=0\r\n def parent(self,i):\r\n if i==0:\r\n return 0\r\n elif i%2==0:\r\n return (i//2)-1\r\n else:\r\n return i//2\r\n def heapify(self,i):\r\n print(self.distv)\r\n left=2*i+1\r\n right=2*(i+1)\r\n if leftself.distv[right]:\r\n x=right\r\n else:\r\n x=left\r\n elif left=self.length:\r\n x=left\r\n elif right=self.length:\r\n x=right\r\n else:\r\n return\r\n if self.distv[i]>self.distv[x]:\r\n t=self.distv[i]\r\n self.distv[i]=self.distv[x]\r\n self.distv[x]=t\r\n temp=self.vertic[i]\r\n self.vertic[i]=self.vertic[x]\r\n self.vertic[x]=temp\r\n self.heapify(x)\r\n def Min(self):\r\n return self.distv[0]\r\n def Insert(self,index,val):\r\n self.vertic.append(index)\r\n self.distv.append(val)\r\n self.length+=1\r\n i=self.length-1\r\n while i>0:\r\n p=self.parent(i)\r\n if self.distv[i]weight[q][r]+a[q].sd:\r\n t=weight[q][r]+a[q].sd\r\n a[graph[q][r]].sd=t\r\n h.update(graph[q][r],t)\r\n a[r].pred=r\r\n for k in range(n):\r\n print(k,a[k].sd)\r\nn=int(input(\"enter No. of vertices :\"))\r\na=[None]*n\r\ngraph=[None]*n\r\nweight=[None]*n\r\nfor i in range(n):\r\n a[i]=Graph()\r\n graph[i]=[]\r\n weight[i]=[]\r\ne=int(input(\"enter No. of edges: \"))\r\nprint(\"enter edges\")\r\ni=0\r\nwhile(i 0 and nums[i] == nums[i - 1]:\n continue\n l, r = i + 1, n - 1\n\n while l < r:\n temp = nums[i] + nums[l] + nums[r]\n if temp == 0:\n result.append([nums[i], nums[l], nums[r]])\n # result += '{},'.format(nums[i])\n # result += '{},'.format(nums[l])\n # result += '{}'.format(nums[r])\n # Finalresult += '{} \\n'.format(result)\n #print(result)\n l += 1\n r -= 1\n while l < r and nums[l] == nums[l - 1]:\n l += 1\n while l < r and nums[r] == nums[r + 1]:\n r -= 1\n elif temp < 0:\n l += 1\n else:\n r -= 1\n #Finalresult += '{}'.format(result)\n #print(Finalresult)\n ans = map(lambda x: ','.join([str(a) for a in x]), result)\n for item in ans:\n Finalresult += '{}\\n'.format(item)\n return Finalresult\n\n\nlist1 = [6, 10, 3, -4, 1, -6, 9]\nprint(threeSum(list1))\n","sub_path":"three-sum.py","file_name":"three-sum.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"515277311","text":"# mqtt_as_timeout.py Implementation of a timeout on publication.\n\n# (C) Copyright 2019 Kevin Köck.\n# Released under the MIT licence.\n\n# This solution detects the case where a publication is delayed by lack of\n# connectivity and cancels it if the delay exceeds a timeout.\n\n# Note that it blocks other attempts at publication while waiting for a PUBACK,\n# counter to the normal operation of the module. A solution capable of handling\n# concurrent qos == 1 publications would require a set instance containing coros.\n\n# It incorporates a workround for the bug in uasyncio V2 whereby cancellation\n# is deferred if a task is waiting on a sleep command.\n# For these reasons it was not included in the mqtt_as module.\n\n# The occurrence of a timeout does not guarantee non-reception of the message:\n# connectivity loss may occur between reception by the broker and reception of\n# CONNACK by the client. However in this case the message would be received in\n# a timely fashion.\n\nfrom mqtt_as import MQTTClient as _MQTTClient\nimport time\nimport uasyncio as asyncio\n\nclass MQTTClient(_MQTTClient):\n _pub_coro = None\n\n # Await broker connection. Subclassed to reduce canceling time from 1s to 50ms\n async def _connection(self):\n while not self._isconnected:\n await asyncio.sleep_ms(50)\n\n async def _publishTimeout(self, topic, msg, retain, qos):\n try:\n await super().publish(topic, msg, retain, qos)\n except asyncio.CancelledError:\n pass\n finally:\n self._pub_coro = None\n\n async def publish(self, topic, msg, retain=False, qos=0, timeout=None):\n coro = None\n start = time.ticks_ms()\n while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout:\n if self._pub_coro is None and coro is None:\n coro = self._publishTimeout(topic, msg, retain, qos)\n asyncio.get_event_loop().create_task(coro)\n self._pub_coro = coro\n elif coro is not None:\n if self._pub_coro != coro:\n return # published\n await asyncio.sleep_ms(20)\n if coro is not None:\n async with self.lock:\n asyncio.cancel(coro)\n return\n","sub_path":"mqtt_as/mqtt_as_timeout.py","file_name":"mqtt_as_timeout.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"525354185","text":"from models.model_gen import ModelGen\nfrom tensorflow.keras import layers\nfrom datetime import datetime\nimport tensorflow as tf\n\n\nclass CnnModel(ModelGen):\n \n def __init__(self):\n super(CnnModel, self).__init__()\n self.conv1 = layers.Conv2D(filters=16,\n kernel_size=9,\n input_shape=(32, 128, 128, 1),\n data_format='channels_last',\n activation='relu',\n name='conv1'\n )\n self.conv2 = layers.Conv2D(32, 5, data_format='channels_last', activation='relu', name='conv2')\n self.conv3 = layers.Conv2D(64, 7, data_format='channels_last', activation='relu', name='conv3')\n self.conv4 = layers.Conv2D(128, 5, data_format='channels_last', activation='relu', name='conv4')\n self.dropout1 = layers.Dropout(0.2, name='drop1')\n self.dropout2 = layers.Dropout(0.2, name='drop2')\n self.dropout3 = layers.Dropout(0.2, name='drop3')\n self.dropout4 = layers.Dropout(0.2, name='drop4')\n self.max_pooling1 = layers.MaxPool2D(2, name='pooling1')\n self.max_pooling2 = layers.MaxPool2D(2, name='pooling2')\n self.max_pooling3 = layers.MaxPool2D(2, name='pooling3')\n self.max_pooling4 = layers.MaxPool2D(2, name='pooling4')\n self.flatten = layers.Flatten(name='flat')\n self.dense = layers.Dense(4, activation='softmax', name='dense')\n \n def call(self, inputs, training=None, mask=None):\n \n inputs = self.conv1(inputs)\n inputs = self.max_pooling1(inputs)\n inputs = self.dropout1(inputs)\n \n inputs = self.conv2(inputs)\n inputs = self.max_pooling2(inputs)\n inputs = self.dropout2(inputs)\n \n inputs = self.conv3(inputs)\n inputs = self.max_pooling3(inputs)\n inputs = self.dropout3(inputs)\n \n inputs = self.conv4(inputs)\n inputs = self.max_pooling4(inputs)\n inputs = self.dropout4(inputs)\n \n inputs = self.flatten(inputs)\n inputs = self.dense(inputs)\n \n return inputs\n\n @property\n def cbs(self):\n cp_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath='saved_params/cnn/checkpoints/{epoch:04d}_ckpt',\n verbose=1,\n save_weights_only=True,\n )\n tb_callback = tf.keras.callbacks.TensorBoard(\n log_dir='saved_params/cnn/tensorboard/' + datetime.now().strftime(\"%Y%m%d-%H%M%S\"),\n histogram_freq=20,\n write_graph=True,\n update_freq='batch'\n )\n es_callback = tf.keras.callbacks.EarlyStopping(\n monitor='accuracy',\n min_delta=0.01,\n patience=15,\n restore_best_weights=True\n )\n \n cbs = [cp_callback, tb_callback, es_callback]\n return cbs\n","sub_path":"models/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"492906904","text":"from operator import itemgetter, attrgetter\nimport sys\nimport boto3\n\ndef get_latest_ami():\n images = []\n ec2_c = boto3.client('ec2')\n #resp = ec2_c.describe_images(Owners=['amazon'], Filters=[{'Name': 'owner-alias', 'Values': ['amazon']}, {'Name': 'name', 'Values': ['amzn2-ami-hvm*2020*gp2']}, {'Name': 'is-public', 'Values': ['true']}, {'Name': 'virtualization-type', 'Values': ['hvm']}, {'Name': 'architecture', 'Values': ['x86_64']}])\n resp = ec2_c.describe_images(Owners=['amazon'], Filters=[{'Name': 'owner-alias', 'Values': ['amazon']}, {'Name': 'name', 'Values': ['*ecs-hvm*']}, {'Name': 'is-public', 'Values': ['true']}, {'Name': 'virtualization-type', 'Values': ['hvm']}, {'Name': 'architecture', 'Values': ['x86_64']}])\n for i in resp['Images']:\n images.append((i['ImageId'], i['CreationDate']))\n images2 = sorted(images, key=itemgetter(1), reverse=True)\n ami_id = images2[0][0]\n #print(images2[0][0], images2[0][1])\n #print(images2)\n return ami_id\n\ndef lets_createlt(myawsvpc, ami_id, key_name):\n mysg_id = None\n mysubnets = []\n mysubnets_tags = {}\n myroutetables = []\n ec2_c = boto3.client('ec2')\n for s in myawsvpc.security_groups.all():\n mysg_id = s.id\n for s in myawsvpc.subnets.all():\n mysubnets.append(s.id)\n for r in myawsvpc.route_tables.all():\n myroutetables.append(r.route_table_id)\n resp = ec2_c.describe_subnets(SubnetIds=mysubnets)\n for s in resp['Subnets']:\n mysubnets_tags.update({s['SubnetId']: s['Tags']})\n #print(mysubnets_tags[mysubnets[0]][0]['Value'])\n #for i in mysubnets:\n for k, v in mysubnets_tags.items():\n #print(k, v)\n if 'Pri' in v[0]['Value']:\n iam_profile = 'EC2BackEndProfile'\n subnetid = k\n else:\n iam_profile = 'EC2FrontEndProfile'\n subnetid = k\n resp = ec2_c.create_launch_template(\n LaunchTemplateData={\n 'ImageId': ami_id,\n 'InstanceType': 't3.large',\n 'IamInstanceProfile': {\n #'Arn':,\n 'Name': iam_profile\n },\n #'SecurityGroupIds': [mysg_id],\n 'KeyName': key_name,\n 'Monitoring': {'Enabled': True},\n 'NetworkInterfaces': [\n {\n 'DeviceIndex': 0,\n 'Groups': [mysg_id],\n 'SubnetId': subnetid\n }\n ],\n 'TagSpecifications': [\n {\n 'ResourceType': 'instance',\n 'Tags': [\n {\n 'Key': 'Name',\n 'Value': 'I-'+v[0]['Value'][8:len(v[0]['Value'])]\n #'Value': 'Instance'+mysubnets_tags[i][0]['Value'][9:len(mysubnets_tags[i][0]['Value'])]\n }\n ]\n }\n ]\n },\n LaunchTemplateName='MyECS' + v[0]['Value'] + 'LaunchTemplate',\n VersionDescription='MyECS' + v[0]['Value'] + 'LaunchTemplateV1',\n #LaunchTemplateName=mysubnets_tags[i][0]['Value'] + 'LaunchTemplate',\n #VersionDescription=mysubnets_tags[i][0]['Value'] + 'LaunchTemplateV1',\n )\n launch_template_id = resp['LaunchTemplate']['LaunchTemplateId']\n print(launch_template_id)\n\ndef main():\n myvpcid = sys.argv[1]\n ec2 = boto3.resource('ec2')\n ami_id = get_latest_ami()\n print(ami_id)\n key_name = 'gregkey'\n myawsvpc = ec2.Vpc(myvpcid)\n lets_createlt(myawsvpc, ami_id, key_name)\n\nif __name__ == '__main__':\n main()\n","sub_path":"myaws_ec2_launch_template.py","file_name":"myaws_ec2_launch_template.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"466276137","text":"#!/usr/bin/env python3\n\r\nimport json\r\nimport os\r\nimport time\r\nimport re\r\nimport sys\r\nimport socket\r\nfrom datetime import datetime\r\nstate = 0\r\npre_state = 0\r\n\r\ndef is_connected():\r\n try:\r\n # connect to the host -- tells us if the host is actually\r\n # reachable\r\n socket.create_connection((\"www.google.com\", 80))\r\n return True\r\n except OSError:\r\n pass\r\n return False\r\n \r\n\r\ntime.sleep(10)\r\n \r\nwhile(1):\r\n if(is_connected()):\r\n state = 1\r\n else:\r\n state = 0\r\n \r\n if state != pre_state:\r\n pre_state = state\r\n time.sleep(0.5)\r\n #restart python server\r\n print(\"[WARN] Restart TFiServer at :: \", datetime.now(),flush=True)\r\n os.system('sudo systemctl stop TFiServer.service')\r\n time.sleep(0.5)\r\n os.system('sudo systemctl start TFiServer.service')\r\n time.sleep(2)","sub_path":"Diag_system.py","file_name":"Diag_system.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"397681180","text":"import boto3\nimport time\nfrom botocore.client import ClientError\nfrom datetime import datetime, timedelta, tzinfo\n\nrds = boto3.client('rds')\n\nclass JST(tzinfo):\n def utcoffset(self, dt):\n return timedelta(hours=9)\n def dst(self, dt):\n return timedelta(0)\n def tzname(self, dt):\n return 'JST'\n\ndef create_snapshot(prefix, instanceid):\n snapshotid = \"-\".join([prefix, datetime.now(tz=JST()).strftime(\"%Y-%m-%dT%H%M\")])\n \n for i in range(0, 5):\n try:\n snapshot = rds.create_db_snapshot(\n DBSnapshotIdentifier=snapshotid,\n DBInstanceIdentifier=instanceid\n )\n return\n except ClientError as e:\n print(str(e))\n time.sleep(1)\n\ndef delete_snapshots(prefix, days):\n snapshots = rds.describe_db_snapshots()\n now = datetime.utcnow().replace(tzinfo=None)\n for snapshot in snapshots['DBSnapshots']:\n # creating snapshot\n if not snapshot.has_key('SnapshotCreateTime'):\n continue\n \n delta = now - snapshot['SnapshotCreateTime'].replace(tzinfo=None)\n if snapshot['DBSnapshotIdentifier'].startswith(prefix) and delta.days >= days:\n rds.delete_db_snapshot(DBSnapshotIdentifier=snapshot['DBSnapshotIdentifier'])\n\ndef lambda_handler(event, context):\n delete_days = 1\n snapshot_prefix = \"manually-snapshot-xxx\"\n instances = [\"xxx-db\"]\n \n for instance in instances:\n create_snapshot(snapshot_prefix, instance)\n \n delete_snapshots(snapshot_prefix, delete_days)\n","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"641081106","text":"# coding: utf-8\nfrom datetime import datetime\nfrom flask import Blueprint, render_template, request, json, get_template_attribute, g, redirect, url_for, abort, \\\n current_app\nfrom ..models import db, Topic, Question, QuestionTopic, FollowTopic, TopicWikiContributor, UserTopicStatistic, \\\n PublicEditLog, TOPIC_EDIT_KIND, Answer, TopicSynonym, UserFeed, ApplyTopicDeletion, HomeFeed, HOME_FEED_KIND\nfrom ..utils.permissions import UserPermission, AdminPermission\nfrom ..utils.helpers import absolute_url_for, text_diff\nfrom ..utils._qiniu import qiniu\nfrom ..utils.decorators import jsonify\nfrom ..forms import AdminTopicForm\n\nbp = Blueprint('topic', __name__)\n\nTOPICS_PER = 45\n\n\n@bp.route('/topic/square')\ndef square():\n \"\"\"话题广场\"\"\"\n config = current_app.config\n\n product_topic = Topic.query.get_or_404(config.get('PRODUCT_TOPIC_ID'))\n product_descendant_topics = product_topic.descendant_topics.order_by(Topic.avg.desc())\n product_total = product_descendant_topics.count()\n\n organization_topic = Topic.query.get_or_404(config.get('ORGANIZATION_TOPIC_ID'))\n organization_descendant_topics = organization_topic.descendant_topics.order_by(Topic.avg.desc())\n organization_total = organization_descendant_topics.count()\n\n position_topic = Topic.query.get_or_404(config.get('POSITION_TOPIC_ID'))\n position_descendant_topics = position_topic.descendant_topics.order_by(Topic.avg.desc())\n position_total = position_descendant_topics.count()\n\n skill_topic = Topic.query.get_or_404(config.get('SKILL_TOPIC_ID'))\n skill_descendant_topics = skill_topic.descendant_topics.order_by(Topic.avg.desc())\n skill_total = skill_descendant_topics.count()\n\n other_descendant_topics = Topic.other_topics()\n other_total = other_descendant_topics.count()\n\n return render_template('topic/square.html', per=TOPICS_PER,\n product_topic=product_topic,\n product_descendant_topics=product_descendant_topics.limit(TOPICS_PER),\n product_total=product_total,\n organization_topic=organization_topic,\n organization_descendant_topics=organization_descendant_topics.limit(TOPICS_PER),\n organization_total=organization_total,\n position_topic=position_topic,\n position_descendant_topics=position_descendant_topics.limit(TOPICS_PER),\n position_total=position_total,\n skill_topic=skill_topic,\n skill_descendant_topics=skill_descendant_topics.limit(TOPICS_PER),\n skill_total=skill_total,\n other_descendant_topics=other_descendant_topics.limit(TOPICS_PER),\n other_total=other_total)\n\n\n@bp.route('/topic/loading_topics_in_square', methods=['POST'])\n@jsonify\ndef loading_topics_in_square():\n \"\"\"在话题广场\"\"\"\n config = current_app.config\n offset = request.args.get('offset', type=int)\n _type = request.args.get('type', 'product')\n\n if not offset:\n return {'result': False}\n\n if _type == 'product':\n descendant_topics = Topic.query.get_or_404(config.get('PRODUCT_TOPIC_ID')).descendant_topics\n elif _type == 'organization':\n descendant_topics = Topic.query.get_or_404(config.get('ORGANIZATION_TOPIC_ID')).descendant_topics\n elif _type == 'position':\n descendant_topics = Topic.query.get_or_404(config.get('POSITION_TOPIC_ID')).descendant_topics\n elif _type == 'skill':\n descendant_topics = Topic.query.get_or_404(config.get('SKILL_TOPIC_ID')).descendant_topics\n else:\n descendant_topics = Topic.other_topics()\n\n descendant_topics = descendant_topics.order_by(Topic.avg.desc()).limit(TOPICS_PER).offset(offset)\n count = descendant_topics.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_topics\")\n return {'result': True, 'html': macro(descendant_topics), 'count': count}\n\n\n@bp.route('/topic/query', methods=['POST'])\n@UserPermission()\n@jsonify\ndef query():\n \"\"\"查询话题\"\"\"\n q = request.form.get('q')\n limit = request.form.get('limit', type=int) # 话题个数限制\n with_create = request.form.get('create') == 'true' # 当找不到名称完全匹配的topic时,是否返回创建选项\n if q:\n topics, _, _ = Topic.query_from_es(q, page=1, per_page=10)\n topics = [topic for topic in topics if topic.merge_to_topic_id is None] # 不显示被合并的话题\n if limit:\n topics = topics[:limit]\n topics_data = [{'name': topic.name, 'id': topic.id, 'avatar_url': topic.avatar_url,\n 'followers_count': topic.followers_count} for topic in topics]\n if with_create:\n exact_topic = Topic.query.filter(Topic.name == q).first() is not None\n if not exact_topic:\n topics_data.insert(0, {'name': q, 'create': True})\n return topics_data\n else:\n return {[]}\n\n\nTOPIC_FANTASTIC_ANSWERS_PER = 15\n\n\n@bp.route('/topic/')\ndef view(uid):\n \"\"\"话题详情页\"\"\"\n topic = Topic.query.get_or_404(uid)\n need_redirect = request.args.get('redirect', type=int)\n from_id = request.args.get('from_id', type=int)\n if from_id:\n from_topic = Topic.query.get_or_404(from_id)\n else:\n from_topic = None\n if topic.merge_to_topic_id and need_redirect != 0:\n return redirect(url_for('.view', uid=topic.merge_to_topic_id, from_id=topic.id))\n answers = topic.all_answers.order_by(Answer.score.desc())\n total = answers.count()\n return render_template('topic/view.html', topic=topic, answers=answers.limit(TOPIC_FANTASTIC_ANSWERS_PER),\n from_topic=from_topic, total=total, per=TOPIC_FANTASTIC_ANSWERS_PER)\n\n\n@bp.route('/topic//loading_fantastic_answers', methods=['POST'])\n@UserPermission()\n@jsonify\ndef loading_fantastic_answers(uid):\n \"\"\"加载话题下的精彩回答\"\"\"\n topic = Topic.query.get_or_404(uid)\n offset = request.args.get('offset', type=int)\n if not offset:\n return {'result': False}\n\n answers = topic.all_answers.order_by(Answer.score.desc()).limit(TOPIC_FANTASTIC_ANSWERS_PER).offset(offset)\n count = answers.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_topic_fantastic_answers\")\n return {'result': True, 'html': macro(answers, topic), 'count': count}\n\n\n@bp.route('/topic//rank')\ndef rank(uid):\n \"\"\"话题榜单\"\"\"\n topic = Topic.query.get_or_404(uid)\n page = request.args.get('page', 1, int)\n experts = UserTopicStatistic.query. \\\n filter(UserTopicStatistic.topic_id == uid,\n UserTopicStatistic.score != 0). \\\n order_by(UserTopicStatistic.week_score.desc()).paginate(page, 15)\n return render_template('topic/rank.html', topic=topic, experts=experts)\n\n\n@bp.route('/topic//wiki')\ndef wiki(uid):\n \"\"\"话题wiki\"\"\"\n topic = Topic.query.get_or_404(uid)\n return render_template('topic/wiki.html', topic=topic)\n\n\n@bp.route('/topic//admin', methods=['POST', 'GET'])\n@UserPermission()\ndef admin(uid):\n \"\"\"话题管理\"\"\"\n topic = Topic.query.get_or_404(uid)\n merged_topics = Topic.query.filter(Topic.merge_to_topic_id == uid)\n uptoken = qiniu.generate_token(policy={\n 'callbackUrl': absolute_url_for('.update_avatar'),\n 'callbackBody': \"id=%d&key=$(key)\" % uid\n })\n return render_template('topic/admin.html', topic=topic, uptoken=uptoken, merged_topics=merged_topics)\n\n\nALL_QUESTIONS_PER = 15\n\n\n@bp.route('/topic//questions')\ndef questions(uid):\n \"\"\"话题下的全部问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n questions = topic.all_questions\n total = questions.count()\n return render_template('topic/questions.html', topic=topic, questions=questions.limit(ALL_QUESTIONS_PER),\n total=total, per=ALL_QUESTIONS_PER)\n\n\n@bp.route('/topic//loading_all_questions', methods=['POST'])\n@UserPermission()\n@jsonify\ndef loading_all_questions(uid):\n \"\"\"加载话题下的全部问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n offset = request.args.get('offset', type=int)\n if not offset:\n return {'result': False}\n\n questions = topic.all_questions.limit(ALL_QUESTIONS_PER).offset(offset)\n count = questions.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_all_questions\")\n return {'result': True, 'html': macro(questions, topic), 'count': count}\n\n\nWAITING_FOR_ANSWER_QUESTIONS_PER = 15\n\n\n@bp.route('/topic//waiting')\ndef waiting_for_answer(uid):\n \"\"\"话题下等待回答的问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n questions = topic.all_questions.filter(Question.answers_count == 0)\n total = questions.count()\n\n return render_template('topic/waiting_for_answer.html', topic=topic,\n questions=questions.limit(WAITING_FOR_ANSWER_QUESTIONS_PER),\n total=total, per=WAITING_FOR_ANSWER_QUESTIONS_PER)\n\n\n@bp.route('/topic//loading_waiting_for_answer_questions', methods=['POST'])\n@UserPermission()\n@jsonify\ndef loading_waiting_for_answer_questions(uid):\n \"\"\"加载话题下的待回答问题\"\"\"\n topic = Topic.query.get_or_404(uid)\n offset = request.args.get('offset', type=int)\n if not offset:\n return {'result': False}\n\n questions = topic.all_questions.filter(Question.answers_count == 0). \\\n limit(WAITING_FOR_ANSWER_QUESTIONS_PER).offset(offset)\n count = questions.count()\n macro = get_template_attribute(\"macros/_topic.html\", \"render_topic_waiting_for_answer_questions\")\n return {'result': True, 'html': macro(questions, topic), 'count': count}\n\n\n@bp.route('/topic//logs')\ndef logs(uid):\n \"\"\"话题日志\"\"\"\n topic = Topic.query.get_or_404(uid)\n return render_template('topic/logs.html', topic=topic)\n\n\n@bp.route('/topic//add_parent_topic', methods=['POST'])\n@UserPermission()\n@jsonify\ndef add_parent_topic(uid):\n \"\"\"添加直接父话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n parent_topic_id = request.form.get('parent_topic_id', type=int)\n name = request.form.get('name', '').strip()\n config = current_app.config\n NC_TOPIC_ID = config.get('NC_TOPIC_ID')\n\n if topic.parent_topics_locked or (parent_topic_id is None and name == ''):\n return {'result': False}\n\n if parent_topic_id:\n parent_topic = Topic.query.get_or_404(parent_topic_id)\n else:\n parent_topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n\n if parent_topic.child_topics_locked:\n return {'result': False}\n\n # 不允许添加以下话题为该话题的直接父话题:\n # 1. 自己\n # 2. 直接父话题\n # 3. 子孙话题\n if parent_topic.id == topic.id \\\n or parent_topic.id in topic.descendant_topics_id_list \\\n or parent_topic.id in topic.parent_topics:\n return {'result': False}\n\n # 若该话题只有一个父话题“未分类”,则将其移除\n parent_topics_id_list = topic.parent_topics_id_list\n if len(parent_topics_id_list) == 1 and parent_topics_id_list[0] == NC_TOPIC_ID and parent_topic.id != NC_TOPIC_ID:\n topic.remove_parent_topic(NC_TOPIC_ID)\n\n topic.add_parent_topic(parent_topic.id)\n\n # MERGE: 若父话题被合并到其他话题,则也将此话题作为子话题添加\n if parent_topic.merge_to_topic_id:\n parent_topic.merge_to_topic.add_child_topic(topic.id, from_merge=True)\n\n # 子话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_PARENT_TOPIC, topic_id=uid, user_id=g.user.id,\n after=parent_topic.name, after_id=parent_topic.id)\n db.session.add(log)\n\n # 父话题 log\n parent_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_CHILD_TOPIC, topic_id=parent_topic.id,\n user_id=g.user.id, after=topic.name, after_id=uid)\n db.session.add(parent_topic_log)\n\n db.session.commit()\n\n macro = get_template_attribute('macros/_topic.html', 'parent_topic_edit_wap')\n return {'result': True, 'html': macro(parent_topic)}\n\n\n@bp.route('/topic//remove_parent_topic/', methods=['POST'])\n@UserPermission()\n@jsonify\ndef remove_parent_topic(uid, parent_topic_id):\n \"\"\"删除直接父话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n parent_topic = Topic.query.get_or_404(parent_topic_id)\n\n if topic.parent_topics_locked or parent_topic.child_topics_locked:\n return {'result': False}\n\n topic.remove_parent_topic(parent_topic_id)\n\n # MERGE: 若父话题被合并到其他话题,则也将此话题作为子话题添加\n if parent_topic.merge_to_topic_id:\n parent_topic.merge_to_topic.remove_child_topic(topic.id, from_merge=True)\n\n # 子话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_PARENT_TOPIC, topic_id=uid, user_id=g.user.id,\n before=parent_topic.name, before_id=parent_topic_id)\n db.session.add(log)\n\n # 父话题 log\n parent_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_CHILD_TOPIC, topic_id=parent_topic.id,\n user_id=g.user.id, before=topic.name, before_id=uid)\n db.session.add(parent_topic_log)\n\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic//add_child_topic', methods=['POST'])\n@UserPermission()\n@jsonify\ndef add_child_topic(uid):\n \"\"\"添加直接子话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n child_topic_id = request.form.get('child_topic_id', type=int)\n name = request.form.get('name', '').strip()\n config = current_app.config\n NC_TOPIC_ID = config.get('NC_TOPIC_ID')\n\n if topic.child_topics_locked or (child_topic_id is None and name == ''):\n return {'result': False}\n\n if child_topic_id:\n child_topic = Topic.query.get_or_404(child_topic_id)\n else:\n child_topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n\n if child_topic.parent_topics_locked:\n return {'result': False}\n\n # 不允许以下的话题添加为该话题的直接子话题\n # 1. 自己\n # 2. 直接子话题\n # 3. 祖先话题\n if child_topic_id == uid \\\n or child_topic_id in topic.ancestor_topics_id_list \\\n or child_topic_id in topic.child_topics_id_list:\n return {'result': False}\n\n # 若子话题只有一个父话题“未分类”,则将其移除\n parent_topics_id_list = child_topic_id.parent_topics_id_list\n if len(parent_topics_id_list) == 1 and parent_topics_id_list[0] == NC_TOPIC_ID and topic.id != NC_TOPIC_ID:\n child_topic.remove_parent_topic(NC_TOPIC_ID)\n\n topic.add_child_topic(child_topic.id)\n\n # MERGE: 若该话题被合并到其他话题,则也进行子话题添加\n if topic.merge_to_topic_id:\n topic.merge_to_topic.add_child_topic(child_topic.id, from_merge=True)\n\n # 父话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_CHILD_TOPIC, topic_id=uid, user_id=g.user.id,\n after=child_topic.name, after_id=child_topic.id)\n db.session.add(log)\n\n # 子话题 log\n child_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_PARENT_TOPIC, topic_id=child_topic.id, user_id=g.user.id,\n after=topic.name, after_id=uid)\n db.session.add(child_topic_log)\n\n db.session.commit()\n\n macro = get_template_attribute('macros/_topic.html', 'child_topic_edit_wap')\n return {'result': True, 'html': macro(child_topic)}\n\n\n@bp.route('/topic//remove_child_topic/', methods=['POST'])\n@UserPermission()\n@jsonify\ndef remove_child_topic(uid, child_topic_id):\n \"\"\"删除直接子话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n child_topic = Topic.query.get_or_404(child_topic_id)\n\n if topic.child_topics_locked or child_topic.parent_topics_locked:\n return {'result': False}\n\n topic.remove_child_topic(child_topic_id)\n\n # MERGE: 若该话题被合并到其他话题,则也进行子话题添加\n if topic.merge_to_topic_id:\n topic.merge_to_topic.remove_child_topic(child_topic.id, from_merge=True)\n\n # 父话题 log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_CHILD_TOPIC, topic_id=uid, user_id=g.user.id,\n before=child_topic.name, before_id=child_topic_id)\n db.session.add(log)\n\n # 子话题 log\n child_topic_log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_PARENT_TOPIC, topic_id=child_topic.id,\n user_id=g.user.id, before=topic.name, before_id=uid)\n db.session.add(child_topic_log)\n\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/get_by_name/', methods=['POST'])\n@UserPermission()\n@jsonify\ndef get_by_name(name):\n \"\"\"通过name获取话题,若不存在则创建\"\"\"\n topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n return {'id': topic.id, 'name': topic.name, 'followers_count': topic.followers_count}\n\n\n@bp.route('/topic//follow', methods=['POST'])\n@UserPermission()\n@jsonify\ndef follow(uid):\n \"\"\"关注 & 取消关注话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n follow_topic = FollowTopic.query.filter(FollowTopic.topic_id == uid,\n FollowTopic.user_id == g.user.id).first()\n # 取消关注\n if follow_topic:\n db.session.delete(follow_topic)\n topic.followers_count -= 1\n db.session.add(topic)\n\n # MERGE: 若该话题合并到其他话题,则也同时取消关注\n if topic.merge_to_topic_id:\n follow_merge_to_topic = topic.merge_to_topic.followers.filter(FollowTopic.user_id == g.user.id,\n FollowTopic.from_merge).first()\n db.session.delete(follow_merge_to_topic)\n topic.merge_to_topic.followers_count -= 1\n db.session.add(topic.merge_to_topic)\n\n # HOME FEED: 从首页 feed 中删除与此话题相关的条目\n for feed in g.user.home_feeds.filter(HomeFeed.topic_id == uid,\n HomeFeed.kind == HOME_FEED_KIND.FANTASTIC_ANSWER_FROM_FOLLOWED_TOPIC):\n db.session.delete(feed)\n\n db.session.commit()\n\n return {'result': True, 'followed': False, 'followers_count': topic.followers_count}\n else:\n # 关注\n follow_topic = FollowTopic(topic_id=uid, user_id=g.user.id)\n db.session.add(follow_topic)\n\n topic.followers_count += 1\n db.session.add(topic)\n\n # MERGE: 若该话题合并到其他话题,则也同时关注\n if topic.merge_to_topic_id:\n follow_merge_to_topic = topic.merge_to_topic.followers.filter(FollowTopic.user_id == g.user.id).first()\n if not follow_merge_to_topic:\n follow_merge_to_topic = FollowTopic(topic_id=topic.merge_to_topic_id, user_id=g.user.id,\n from_merge=True)\n db.session.add(follow_merge_to_topic)\n topic.merge_to_topic.followers_count += 1\n db.session.add(topic.merge_to_topic)\n\n # USER FEED: 关注话题\n UserFeed.follow_topic(g.user, topic)\n\n # HOME FEED: 向首页 feed 中插入该话题的精彩回答 10 条\n for answer in topic.all_answers.filter(Answer.fantastic).order_by(Answer.created_at.desc()).limit(5):\n home_feed = g.user.home_feeds.filter(HomeFeed.kind == HOME_FEED_KIND.FANTASTIC_ANSWER_FROM_FOLLOWED_TOPIC,\n HomeFeed.answer_id == answer.id).first()\n if not home_feed:\n home_feed = HomeFeed(kind=HOME_FEED_KIND.FANTASTIC_ANSWER_FROM_FOLLOWED_TOPIC, answer_id=answer.id,\n user_id=g.user.id, topic_id=topic.id)\n db.session.add(home_feed)\n\n db.session.commit()\n\n return {'result': True, 'followed': True, 'followers_count': topic.followers_count}\n\n\n@bp.route('/topic//add_synonym', methods=['POST'])\n@jsonify\ndef add_synonym(uid):\n \"\"\"添加话题同义词\"\"\"\n topic = Topic.query.get_or_404(uid)\n synonym = request.form.get('synonym')\n if synonym:\n topic_synonym = topic.synonyms.filter(TopicSynonym.synonym == synonym).first()\n if not topic_synonym:\n topic_synonym = TopicSynonym(synonym=synonym)\n topic.synonyms.append(topic_synonym)\n db.session.add(topic)\n\n # log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.ADD_SYNONYM, after=synonym,\n user_id=g.user.id, topic_id=uid)\n db.session.add(log)\n db.session.commit()\n topic.save_to_es()\n macro = get_template_attribute('macros/_topic.html', 'topic_synonym_edit_wap')\n return {'result': True, 'html': macro(topic_synonym)}\n else:\n return {'result': False}\n else:\n return {'result': False}\n\n\n@bp.route('/topic/synonym//remove', methods=['POST'])\n@jsonify\ndef remove_synonym(uid):\n \"\"\"移除话题同义词\"\"\"\n topic_synonym = TopicSynonym.query.get_or_404(uid)\n\n # log\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.REMOVE_SYNONYM, before=topic_synonym.synonym,\n user_id=g.user.id, topic_id=topic_synonym.topic_id)\n db.session.add(log)\n db.session.delete(topic_synonym)\n topic_synonym.topic.save_to_es()\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic//update_experience', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_experience(uid):\n \"\"\"更新当前用户在该话题下的话题经验\"\"\"\n topic = Topic.query.get_or_404(uid)\n experience = request.form.get('experience', '')\n from_compose = request.form.get('compose', type=int) == 1\n\n statistic = UserTopicStatistic.query.filter(UserTopicStatistic.topic_id == uid,\n UserTopicStatistic.user_id == g.user.id).first()\n if statistic:\n statistic.experience = experience\n else:\n statistic = UserTopicStatistic(topic_id=uid, user_id=g.user.id, experience=experience)\n db.session.add(statistic)\n\n if not g.user.has_selected_expert_topics:\n for expert in g.user.expert_topics:\n expert.selected = True\n db.session.add(expert)\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic//apply_for_deletion', methods=['POST'])\n@UserPermission()\n@jsonify\ndef apply_for_deletion(uid):\n \"\"\"申请删除话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n apply = ApplyTopicDeletion(user_id=g.user.id, topic_id=uid)\n db.session.add(apply)\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/expert//remove', methods=['POST'])\n@UserPermission()\n@jsonify\ndef remove_expert(uid):\n \"\"\"移除擅长话题\"\"\"\n expert_topic = UserTopicStatistic.query.get_or_404(uid)\n if not g.user.has_selected_expert_topics:\n for expert in g.user.expert_topics:\n expert.selected = True\n db.session.add(expert)\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n db.session.commit()\n expert_topic.selected = False\n db.session.add(expert_topic)\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic/add_expert', methods=['POST'])\n@UserPermission()\n@jsonify\ndef add_expert():\n \"\"\"添加擅长话题\"\"\"\n # 最多设置 8 个擅长话题\n if g.user.expert_topics.count() == 8:\n return {'result': True}\n\n id = request.form.get('id', type=int)\n name = request.form.get('name', '').strip()\n\n if id:\n topic = Topic.query.get_or_404(id)\n else:\n topic = Topic.get_by_name(name, g.user.id, create_if_not_exist=True)\n\n new_expert_topic = UserTopicStatistic.query.filter(UserTopicStatistic.topic_id == topic.id,\n UserTopicStatistic.user_id == g.user.id).first()\n if not new_expert_topic:\n new_expert_topic = UserTopicStatistic(topic_id=topic.id, user_id=g.user.id, selected=True)\n db.session.add(new_expert_topic)\n else:\n if new_expert_topic.selected:\n return {'result': True}\n else:\n new_expert_topic.selected = True\n\n if not g.user.has_selected_expert_topics:\n max_show_order_topic = 0\n for index, expert_topic in enumerate(g.user.expert_topics):\n expert_topic.show_order = index\n expert_topic.selected = True\n db.session.add(expert_topic)\n max_show_order_topic = index\n new_expert_topic.show_order = max_show_order_topic + 1\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n db.session.add(new_expert_topic)\n else:\n max_show_order_topic = g.user.expert_topics.from_self().order_by(UserTopicStatistic.show_order.desc()).first()\n if max_show_order_topic:\n new_expert_topic.show_order = max_show_order_topic.show_order + 1\n\n db.session.commit()\n\n macro = get_template_attribute(\"macros/_topic.html\", \"render_expert_topic\")\n return {\n 'result': True,\n 'html': macro(new_expert_topic, myself=True),\n 'full': g.user.expert_topics.count() == 8\n }\n\n\n@bp.route('/topic/update_show_order', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_show_order():\n show_orders = request.form.get('show_orders')\n if not show_orders:\n return {'result': True}\n\n # 若从未编辑过擅长话题,则首先赋予 show_order\n if not g.user.has_selected_expert_topics:\n for index, expert_topic in enumerate(g.user.expert_topics):\n expert_topic.show_order = index\n expert_topic.selected = True\n db.session.add(expert_topic)\n\n g.user.has_selected_expert_topics = True\n db.session.add(g.user)\n\n show_orders = json.loads(show_orders)\n for item in show_orders:\n id = item['id']\n show_order = item['show_order']\n expert_topic = UserTopicStatistic.query.get(id)\n if expert_topic:\n expert_topic.show_order = show_order\n db.session.add(expert_topic)\n\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic//get_data_for_card', methods=['POST'])\n@jsonify\ndef get_data_for_card(uid):\n \"\"\"获取话题卡片\"\"\"\n topic = Topic.query.get_or_404(uid)\n return {\n 'result': True,\n 'topic': {\n 'id': uid,\n 'name': topic.name,\n 'url': url_for('.view', uid=uid),\n 'avatar_url': topic.avatar_url,\n 'followers_count': topic.followers_count,\n 'followed': bool(g.user and topic.followed_by_user(g.user.id)),\n 'wiki_preview': topic.wiki_preview\n }\n }\n\n\n@bp.route('/topic/update_avatar', methods=['POST'])\n@jsonify\ndef update_avatar():\n \"\"\"更新话题头像\"\"\"\n id = request.form.get('id', type=int)\n topic = Topic.query.get_or_404(id)\n\n if topic.avatar_locked:\n return {'result': False}\n\n avatar = request.form.get('key')\n topic.avatar = avatar\n db.session.add(topic)\n db.session.commit()\n return {'result': True, 'url': topic.avatar_url, 'id': topic.id}\n\n\n@bp.route('/topic//edit_wiki', methods=['GET', 'POST'])\ndef edit_wiki(uid):\n \"\"\"编辑话题百科\"\"\"\n topic = Topic.query.get_or_404(uid)\n\n if topic.wiki_locked:\n abort(403)\n\n form = AdminTopicForm()\n if form.validate_on_submit():\n # Update wiki log\n if (topic.wiki or \"\") != form.wiki.data:\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.UPDATE_WIKI, user_id=g.user.id, topic_id=uid,\n before=topic.wiki, after=form.wiki.data,\n compare=text_diff(topic.wiki, form.wiki.data))\n db.session.add(log)\n\n # 记录wiki贡献者\n contributor = topic.wiki_contributors.filter(TopicWikiContributor.user_id == g.user.id).first()\n if contributor:\n contributor.count += 1\n contributor.last_contributed_at = datetime.now()\n db.session.add(contributor)\n else:\n contributor = TopicWikiContributor(topic_id=uid, user_id=g.user.id, count=1)\n db.session.add(contributor)\n\n form.populate_obj(topic)\n db.session.add(topic)\n db.session.commit()\n topic.save_to_es()\n return redirect(url_for('.view', uid=uid))\n return render_template('topic/edit_wiki.html', topic=topic)\n\n\n@bp.route('/topic//update_name', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_name(uid):\n \"\"\"更新话题名称\"\"\"\n topic = Topic.query.get_or_404(uid)\n name = request.form.get('name', '').strip()\n\n if topic.name_locked or not name:\n return {'result': False}\n\n # 话题名称不可重复\n if Topic.query.filter(Topic.name == name, Topic.id != uid).first():\n return {'result': False}\n\n # Update name log\n if topic.name != name:\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.UPDATE_NAME, user_id=g.user.id, topic_id=uid, before=topic.name,\n after=name)\n db.session.add(log)\n\n topic.name = name\n topic.save_to_es()\n db.session.add(topic)\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic//lock', methods=['POST'])\n@AdminPermission()\n@jsonify\ndef lock(uid):\n \"\"\"锁定话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n target = request.form.get('target')\n\n if not target:\n return {'result': True}\n\n attr = '%s_locked' % target\n\n if not hasattr(topic, attr):\n return {'result': True}\n\n locked = bool(getattr(topic, attr))\n setattr(topic, attr, not locked)\n\n # log\n log = PublicEditLog(user_id=g.user.id, topic_id=uid)\n if locked:\n log.kind = TOPIC_EDIT_KIND.UNLOCK\n log.before = attr\n else:\n log.kind = TOPIC_EDIT_KIND.LOCK\n log.after = attr\n db.session.add(log)\n\n if target == 'all':\n if topic.all_locked:\n topic.avatar_locked = True\n topic.name_locked = True\n topic.wiki_locked = True\n topic.parent_topics_locked = True\n topic.child_topics_locked = True\n topic.merge_topic_locked = True\n topic.topic_kind_locked = True\n else:\n topic.avatar_locked = False\n topic.name_locked = False\n topic.wiki_locked = False\n topic.parent_topics_locked = False\n topic.child_topics_locked = False\n topic.merge_topic_locked = False\n topic.topic_kind_locked = False\n\n if topic.avatar_locked and topic.name_locked and topic.wiki_locked and topic.parent_topics_locked \\\n and topic.child_topics_locked and topic.merge_topic_locked and topic.topic_kind_locked:\n topic.all_locked = True\n else:\n topic.all_locked = False\n\n db.session.add(topic)\n db.session.commit()\n\n return {'result': True, 'locked': not locked}\n\n\n@bp.route('/topic//update_kind', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_kind(uid):\n \"\"\"更新话题类型\"\"\"\n topic = Topic.query.get_or_404(uid)\n kind = request.form.get('kind', type=int)\n\n if topic.topic_kind_locked or not kind or kind < 1 or kind > 6:\n return {'result': False}\n\n # log\n if topic.kind != kind:\n log = PublicEditLog(kind=TOPIC_EDIT_KIND.UPDATE_KIND, user_id=g.user.id, before=topic.kind,\n after=kind, topic_id=uid)\n db.session.add(log)\n\n topic.kind = kind\n db.session.add(topic)\n db.session.commit()\n\n return {'result': True}\n\n\n@bp.route('/topic//update_other_kind', methods=['POST'])\n@UserPermission()\n@jsonify\ndef update_other_kind(uid):\n \"\"\"更新话题其他类型\"\"\"\n topic = Topic.query.get_or_404(uid)\n kind = request.form.get('kind', '').strip()\n topic.other_kind = kind\n db.session.add(topic)\n db.session.commit()\n return {'result': True}\n\n\n@bp.route('/topic//merge_to', methods=['POST'])\n@AdminPermission()\n@jsonify\ndef merge_to(uid):\n \"\"\"将本话题合并至另一话题\"\"\"\n topic = Topic.query.get_or_404(uid)\n\n if topic.merge_topic_locked or topic.merge_to_topic_id:\n return {'result': False}\n\n merge_to_topic_id = request.form.get('merge_to_topic_id', type=int)\n name = request.form.get('name', '').strip()\n\n if merge_to_topic_id:\n if uid == merge_to_topic_id:\n return {'result': False}\n merge_to_topic = Topic.query.get_or_404(merge_to_topic_id)\n else:\n merge_to_topic = Topic.get_by_name(name)\n if not merge_to_topic:\n return {'result': False}\n\n topic.merge_to_topic_id = merge_to_topic.id\n\n # 话题类型统一为与 merge_to_topic 一致,并锁定\n topic.kind = merge_to_topic.kind\n topic.other_kind = merge_to_topic.other_kind\n topic.topic_kind_locked = True\n db.session.add(topic)\n\n # 将该话题的名称设为 merge_to_topic 的同义词\n topic_synonym = merge_to_topic.synonyms.filter(TopicSynonym.synonym == topic.name).first()\n if not topic_synonym:\n topic_synonym = TopicSynonym(synonym=topic.name, topic_id=merge_to_topic.id, from_merge=True)\n db.session.add(topic_synonym)\n merge_to_topic.save_to_es()\n\n # 迁移问题\n for question_topic in topic.questions:\n _question_topic = merge_to_topic.questions.filter(\n QuestionTopic.question_id == question_topic.question_id).first()\n if not _question_topic:\n _question_topic = QuestionTopic(question_id=question_topic.question_id, topic_id=merge_to_topic.id,\n from_merge=True)\n db.session.add(_question_topic)\n\n # 迁移子话题\n for child_topic_id in topic.child_topics_id_list:\n merge_to_topic.add_child_topic(child_topic_id, from_merge=True)\n\n # 迁移关注者\n for follow_topic in topic.followers:\n _topic_follower = merge_to_topic.followers.filter(FollowTopic.user_id == follow_topic.user_id).first()\n if not _topic_follower:\n _topic_follower = FollowTopic(topic_id=merge_to_topic.id, user_id=follow_topic.user_id,\n from_merge=True)\n db.session.add(_topic_follower)\n merge_to_topic.followers_count += 1\n db.session.add(merge_to_topic)\n\n # 被合并的话题 Log\n merge_to_log = PublicEditLog(kind=TOPIC_EDIT_KIND.MERGE_TO, user_id=g.user.id, topic_id=uid,\n after_id=merge_to_topic.id, after=merge_to_topic.name)\n db.session.add(merge_to_log)\n\n # 合并至的话题 Log\n merge_in_log = PublicEditLog(kind=TOPIC_EDIT_KIND.MERGE_IN, user_id=g.user.id, topic_id=merge_to_topic.id,\n after_id=uid, after=topic.name)\n db.session.add(merge_in_log)\n\n db.session.commit()\n return {'id': merge_to_topic.id, 'name': merge_to_topic.name, 'result': True}\n\n\n@bp.route('/topic//unmerge_from/', methods=['POST'])\n@AdminPermission()\n@jsonify\ndef unmerge_from(uid, unmerge_from_topic_id):\n \"\"\"取消话题合并\"\"\"\n topic = Topic.query.get_or_404(uid)\n unmerge_from_topic = Topic.query.get_or_404(unmerge_from_topic_id)\n\n if topic.merge_topic_locked or topic.merge_to_topic_id != unmerge_from_topic_id:\n return {'result': False}\n\n topic.merge_to_topic_id = None\n\n # 解锁话题类型\n topic.topic_kind_locked = False\n\n # 移除同义词\n topic_synonym = unmerge_from_topic.synonyms.filter(TopicSynonym.synonym == topic.name,\n TopicSynonym.from_merge).first()\n unmerge_from_topic.save_to_es()\n\n db.session.delete(topic_synonym)\n\n # 迁回问题\n for question_topic in topic.questions:\n _question_topic = unmerge_from_topic.questions.filter(QuestionTopic.question_id == question_topic.question_id,\n QuestionTopic.from_merge).first()\n db.session.delete(_question_topic)\n\n # 迁回子话题\n for child_topic_id in topic.child_topics_id_list:\n unmerge_from_topic.remove_child_topic(child_topic_id, from_merge=True)\n\n # 迁回关注者\n for follow_topic in topic.followers:\n _topic_follower = unmerge_from_topic.followers.filter(FollowTopic.user_id == follow_topic.user_id,\n FollowTopic.from_merge).first()\n if _topic_follower:\n db.session.delete(_topic_follower)\n unmerge_from_topic.followers_count -= 1\n db.session.add(unmerge_from_topic)\n\n db.session.add(topic)\n\n # 取消合并至话题 log\n unmerge_from_log = PublicEditLog(kind=TOPIC_EDIT_KIND.UNMERGE_FROM, user_id=g.user.id,\n topic_id=uid, before=unmerge_from_topic.name,\n before_id=unmerge_from_topic.id)\n db.session.add(unmerge_from_log)\n\n # 从话题中移出 log\n unmerge_out_log = PublicEditLog(kind=TOPIC_EDIT_KIND.UNMERGE_OUT, user_id=g.user.id,\n topic_id=unmerge_from_topic.id, before=topic.name,\n before_id=topic.id)\n db.session.add(unmerge_out_log)\n\n db.session.commit()\n\n return {'result': True}\n","sub_path":"application/controllers/topic.py","file_name":"topic.py","file_ext":"py","file_size_in_byte":37834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"133921397","text":"class Solution(object):\n def flipAndInvertImage(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n results = []\n for i in range(len(A)):\n row = []\n for j in range(len(A[i])-1, -1, -1):\n row.append(0 if A[i][j] == 1 else 1)\n results.append(row)\n return results\n","sub_path":"Python/832. Flipping an Image.py","file_name":"832. Flipping an Image.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"384010443","text":"#\n# Pyserini: Python interface to the Anserini IR toolkit built on Lucene\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport filecmp\nimport unittest\nfrom tqdm import tqdm\nfrom pyserini.fusion import FusionMethod\nfrom pyserini.trectools import TrecRun\nfrom pyserini.search import get_topics, SimpleFusionSearcher, SimpleSearcher\n\n\nclass TestSearchIntegration(unittest.TestCase):\n def setUp(self):\n if not os.path.exists('lucene-index-cord19-abstract-2020-05-01/'):\n os.system('wget -nc https://www.dropbox.com/s/wxjoe4g71zt5za2/lucene-index-cord19-abstract-2020-05-01.tar.gz')\n os.system('tar -xvzf lucene-index-cord19-abstract-2020-05-01.tar.gz')\n os.system('rm lucene-index-cord19-abstract-2020-05-01.tar.gz')\n\n if not os.path.exists('lucene-index-cord19-full-text-2020-05-01/'):\n os.system('wget -nc https://www.dropbox.com/s/di27r5o2g5kat5k/lucene-index-cord19-full-text-2020-05-01.tar.gz')\n os.system('tar -xvzf lucene-index-cord19-full-text-2020-05-01.tar.gz')\n os.system('rm lucene-index-cord19-full-text-2020-05-01.tar.gz')\n\n if not os.path.exists('lucene-index-cord19-paragraph-2020-05-01/'):\n os.system('wget -nc https://www.dropbox.com/s/6ib71scm925mclk/lucene-index-cord19-paragraph-2020-05-01.tar.gz')\n os.system('tar -xvzf lucene-index-cord19-paragraph-2020-05-01.tar.gz')\n os.system('rm lucene-index-cord19-paragraph-2020-05-01.tar.gz')\n\n if not os.path.exists('anserini.covid-r2.fusion1.txt'):\n os.system('wget -q -nc https://www.dropbox.com/s/wqb0vhxp98g7dxh/anserini.covid-r2.fusion1.txt.gz')\n os.system('gunzip -f anserini.covid-r2.fusion1.txt.gz')\n\n def test_simple_fusion_searcher(self):\n index_dirs = ['lucene-index-cord19-abstract-2020-05-01/',\n 'lucene-index-cord19-full-text-2020-05-01/',\n 'lucene-index-cord19-paragraph-2020-05-01/']\n\n searcher = SimpleFusionSearcher(index_dirs, method=FusionMethod.RRF)\n\n runs, topics = [], get_topics('covid_round2')\n for topic in tqdm(sorted(topics.keys())):\n query = topics[topic]['question'] + ' ' + topics[topic]['query']\n hits = searcher.search(query, k=10000, query_generator=None, strip_segment_id=True, remove_dups=True)\n docid_score_pair = [(hit.docid, hit.score) for hit in hits]\n run = TrecRun.from_search_results(docid_score_pair, topic=topic)\n runs.append(run)\n\n all_topics_run = TrecRun.concat(runs)\n all_topics_run.save_to_txt(output_path='fused.txt', tag='reciprocal_rank_fusion_k=60')\n\n # Only keep topic, docid and rank. Scores have different floating point precisions.\n os.system(\"\"\"awk '{print $1\" \"$3\" \"$4}' fused.txt > this.txt\"\"\")\n os.system(\"\"\"awk '{print $1\" \"$3\" \"$4}' anserini.covid-r2.fusion1.txt > that.txt\"\"\")\n\n self.assertTrue(filecmp.cmp('this.txt', 'that.txt'))\n\n def tearDown(self):\n os.system('rm anserini.covid-r2.fusion1.txt fused.txt this.txt that.txt')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"integrations/test_search_integration.py","file_name":"test_search_integration.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"81147933","text":"__author__ = 'loliveira'\n\nfrom flask import g, jsonify\nfrom flask_restful import Resource\n\nfrom app import db\nfrom conf.auth import auth\nfrom app.resources import parser\nfrom app.models.UserModel import Task\nfrom datetime import date\n\n\nclass TaskResource(Resource):\n\n @staticmethod\n @auth.login_required\n def get():\n parser.add_argument('done', type=int)\n args = parser.parse_args() \n done = args['done']\n response = []\n\n for task in g.user.tasks:\n add = False \n if done is not None:\n if task.done == done:\n add = True\n else:\n add = True\n\n if add:\n task_json = dict(id=task.id, title=task.title, description=task.description,difficulty=task.difficulty,priority=task.priority,done=task.done,end_date=str(task.end_date),start_date=str(task.start_date))\n response.extend([task_json])\n return jsonify(tasks=response)\n\n @staticmethod\n @auth.login_required\n def put():\n parser.add_argument('title', type=str)\n parser.add_argument('description', type=str)\n parser.add_argument('difficulty', type=int)\n parser.add_argument('priority', type=int)\n parser.add_argument('done', type=bool)\n parser.add_argument('end_date', type=str)\n parser.add_argument('start_date', type=str)\n args = parser.parse_args()\n task = Task(args['title'], args['description'], args['priority'], args['done'], args['difficulty'],args['end_date'],args['start_date'])\n task.user = g.user.id\n db.session.add(task)\n db.session.commit()\n\n return jsonify({'task': task.id})\n pass\n\n\n\nclass SingleTaskResource(Resource):\n\n @staticmethod\n @auth.login_required\n def get(task_id):\n task = Task.query.get(task_id)\n if task is None:\n return {}, 404\n if task.user == g.user.id:\n return jsonify(dict(id=task.id, title=task.title, description=task.description,difficulty=task.difficulty,priority=task.priority,done=task.done,end_date=str(task.end_date)),start_date=str(task.start_date))\n else:\n return {}, 404\n\n @staticmethod\n @auth.login_required\n def delete(task_id):\n task = Task.query.get(task_id)\n if task.user == g.user.id:\n db.session.delete(task)\n db.session.commit()\n return jsonify({'operation_status': 'SUCCESS'})\n else:\n return {}\n\n @staticmethod\n @auth.login_required\n def post(task_id):\n parser.add_argument('title', type=str)\n parser.add_argument('description', type=str)\n parser.add_argument('priority', type=int)\n parser.add_argument('done', type=str)\n parser.add_argument('difficulty', type=int)\n parser.add_argument('start_date', type=str)\n parser.add_argument('end_date', type=str)\n args = parser.parse_args()\n\n task = Task.query.get(task_id)\n updated = []\n title = args['title']\n if title is not None:\n updated.append('title')\n task.title = args['title']\n\n description = args['description']\n if description is not None:\n updated.append('description')\n task.description = description\n\n priority = args['priority']\n if priority is not None:\n updated.append('priority')\n task.priority = priority\n\n done = args['done']\n if done is not None:\n updated.append('done')\n task.done = done\n\n difficulty = args['difficulty']\n if difficulty is not None:\n updated.append('difficulty')\n task.difficulty = difficulty\n\n start_date = args['start_date']\n if start_date is not None:\n updated.append('start_date')\n task.start_date = start_date\n\n end_date = args['end_date']\n if end_date is not None:\n updated.append('end_date')\n task.end_date = end_date\n\n db.session.add(task)\n db.session.commit()\n\n return jsonify({'operation_status': 'SUCCESS', 'updated_values': updated})\n\n","sub_path":"app/resources/task_resource.py","file_name":"task_resource.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"283297734","text":"import cv2 as cv\n\n\nclass StereoParams:\n def __init__(self, intrinsic_filepath, extrinsic_filepath, image_size=None):\n if image_size is None:\n self._image_size = (752, 480)\n else:\n self._image_size = (image_size[0], image_size[1])\n\n intrinsic_file = cv.FileStorage(intrinsic_filepath, cv.FileStorage_READ)\n if not intrinsic_file.isOpened():\n raise ValueError('Cannot open intrinsic file')\n\n extrinsic_file = cv.FileStorage(extrinsic_filepath, cv.FileStorage_READ)\n if not extrinsic_file.isOpened():\n raise ValueError('Cannot open extrinsic file')\n\n self._M1 = intrinsic_file.getNode('M1').mat()\n self._D1 = intrinsic_file.getNode('D1').mat()\n self._M2 = intrinsic_file.getNode('M2').mat()\n self._D2 = intrinsic_file.getNode('D2').mat()\n\n self._R = extrinsic_file.getNode('R').mat()\n self._T = extrinsic_file.getNode('T').mat()\n\n r = cv.stereoRectify(self._M1, self._D1, self._M2, self._D2, self._image_size,\n self._R, self._T, flags=cv.CALIB_ZERO_DISPARITY)\n self._R1, self._R2, self._P1, self._P2, _, _, _ = r\n\n self._map11, self._map12 = cv.initUndistortRectifyMap(\n self._M1, self._D1, self._R1, self._P1, self._image_size, cv.CV_16SC2)\n self._map21, self._map22 = cv.initUndistortRectifyMap(\n self._M2, self._D2, self._R2, self._P2, self._image_size, cv.CV_16SC2)\n\n def _remap(self, image, map1, map2):\n resized = False\n orig_size = (image.shape[1], image.shape[0])\n if orig_size != self._image_size:\n image = cv.resize(image, self._image_size)\n resized = True\n\n image = cv.remap(image, map1, map2, cv.INTER_LINEAR)\n\n if resized:\n image = cv.resize(image, orig_size)\n\n return image\n\n def remap_left(self, image):\n return self._remap(image, self._map11, self._map12)\n\n def remap_right(self, image):\n return self._remap(image, self._map21, self._map22)\n","sub_path":"stereo/_stereo_params.py","file_name":"_stereo_params.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"564392169","text":"from gevent import monkey # isort:skip\nmonkey.patch_all() # isort:skip\n\nimport timeit # noqa: E402\n\nfrom gevent import sleep # noqa: E402\nfrom simple_amqp import AmqpParameters # noqa: E402\n\nfrom simple_amqp_pubsub import Event, Pipe, Source, Subscriber # noqa: E402\nfrom simple_amqp_pubsub.gevent import GeventAmqpPubSub # noqa: E402\n\npubsub_conn = GeventAmqpPubSub(\n params=AmqpParameters(),\n)\n\nLOGS_SOURCE = Source(name='logs')\nLOGS_PIPE = Pipe(\n name='logs.worker',\n retries=['5s', '10s', '30s'],\n)\n\n\nclass LogService:\n sub = Subscriber(LOGS_PIPE)\n\n def __init__(self):\n self._last_dt = timeit.default_timer()\n\n @sub.listen(LOGS_SOURCE, 'logs')\n def logs(self, event: Event):\n log_line = event.payload\n\n print('## log line: ', log_line)\n time = timeit.default_timer()\n print('## dt {0:.2f}ms'.format((time - self._last_dt) * 1000))\n self._last_dt = time\n\n\nlogs_service = LogService()\npubsub_conn \\\n .add_subscriber(logs_service.sub, logs_service)\n\npubsub_conn.configure()\npubsub_conn.start()\n\nwhile True:\n sleep(1)\n","sub_path":"examples/gevent/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"611878969","text":"import unittest\n\n\nclass TestExercise(unittest.TestCase):\n MESSAGE_FMT = 'Đầu vào: {0!r} - Kết quả đúng là {1!r}, nhận được {2!r}'\n\n def _test_all(self, func, cases):\n for input_, expect in cases:\n output = func(input_)\n msg = self.MESSAGE_FMT.format(input_, expect, output)\n self.assertEqual(output, expect, msg)\n","sub_path":"pyfml/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"536652356","text":"# Copyright 2013 IBM Corp.\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\nfrom __future__ import print_function\n\nimport os\nimport os.path\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport testtools\n\n\ndef _file_to_list(fname):\n with open(fname) as f:\n content = list(map(lambda x: x.rstrip(), f.readlines()))\n print(content)\n return content\n\n\nclass UpdateTest(testtools.TestCase):\n\n def setUp(self):\n super(UpdateTest, self).setUp()\n self.dir = tempfile.mkdtemp()\n self.project_dir = os.path.join(self.dir, \"project\")\n self.bad_project_dir = os.path.join(self.dir, \"bad_project\")\n self.oslo_dir = os.path.join(self.dir, \"project_with_oslo\")\n\n self.req_file = os.path.join(self.dir, \"global-requirements.txt\")\n self.dev_req_file = os.path.join(self.dir, \"dev-requirements.txt\")\n self.proj_file = os.path.join(self.project_dir, \"requirements.txt\")\n self.oslo_file = os.path.join(self.oslo_dir, \"requirements.txt\")\n self.bad_proj_file = os.path.join(self.bad_project_dir,\n \"requirements.txt\")\n self.proj_test_file = os.path.join(self.project_dir,\n \"test-requirements.txt\")\n self.setup_file = os.path.join(self.project_dir, \"setup.py\")\n self.old_setup_file = os.path.join(self.oslo_dir, \"setup.py\")\n self.bad_setup_file = os.path.join(self.bad_project_dir, \"setup.py\")\n self.setup_cfg_file = os.path.join(self.project_dir, \"setup.cfg\")\n self.bad_setup_cfg_file = os.path.join(self.bad_project_dir,\n \"setup.cfg\")\n self.oslo_setup_cfg_file = os.path.join(self.oslo_dir, \"setup.cfg\")\n os.mkdir(self.project_dir)\n os.mkdir(self.oslo_dir)\n os.mkdir(self.bad_project_dir)\n\n shutil.copy(\"tests/files/gr-base.txt\", self.req_file)\n shutil.copy(\"tests/files/dev-req.txt\", self.dev_req_file)\n shutil.copy(\"tests/files/project-with-oslo-tar.txt\", self.oslo_file)\n shutil.copy(\"tests/files/project.txt\", self.proj_file)\n shutil.copy(\"tests/files/project-with-bad-requirement.txt\",\n self.bad_proj_file)\n shutil.copy(\"tests/files/test-project.txt\", self.proj_test_file)\n shutil.copy(\"tests/files/setup.py\", self.setup_file)\n shutil.copy(\"tests/files/setup.py\", self.bad_setup_file)\n shutil.copy(\"tests/files/old-setup.py\", self.old_setup_file)\n shutil.copy(\"tests/files/setup.cfg\", self.setup_cfg_file)\n shutil.copy(\"tests/files/setup.cfg\", self.bad_setup_cfg_file)\n shutil.copy(\"tests/files/setup.cfg\", self.oslo_setup_cfg_file)\n shutil.copy(\"update.py\", os.path.join(self.dir, \"update.py\"))\n\n # now go call update and see what happens\n self.addCleanup(os.chdir, os.path.abspath(os.curdir))\n os.chdir(self.dir)\n returncode = subprocess.call([sys.executable, \"update.py\", \"project\"])\n self.assertEqual(returncode, 0)\n returncode = subprocess.call([sys.executable, \"update.py\",\n \"project_with_oslo\"])\n self.assertEqual(returncode, 0)\n\n def test_requirements(self):\n reqs = _file_to_list(self.req_file)\n self.assertIn(\"jsonschema>=1.0.0,!=1.4.0,<2\", reqs)\n\n def test_project(self):\n reqs = _file_to_list(self.proj_file)\n # ensure various updates take\n self.assertIn(\"jsonschema>=1.0.0,!=1.4.0,<2\", reqs)\n self.assertIn(\"python-keystoneclient>=0.4.1\", reqs)\n self.assertIn(\"SQLAlchemy>=0.7,<=0.7.99\", reqs)\n\n def test_project_with_oslo(self):\n reqs = _file_to_list(self.oslo_file)\n oslo_tar = (\"-f http://tarballs.openstack.org/oslo.config/\"\n \"oslo.config-1.2.0a3.tar.gz#egg=oslo.config-1.2.0a3\")\n self.assertIn(oslo_tar, reqs)\n self.assertIn(\"oslo.config>=1.2.0a3\", reqs)\n self.assertNotIn(\"oslo.config>=1.1.0\", reqs)\n\n def test_test_project(self):\n reqs = _file_to_list(self.proj_test_file)\n self.assertIn(\"testtools>=0.9.32\", reqs)\n self.assertIn(\"testrepository>=0.0.17\", reqs)\n # make sure we didn't add something we shouldn't\n self.assertNotIn(\"sphinxcontrib-pecanwsme>=0.2\", reqs)\n\n def test_install_setup(self):\n setup_contents = _file_to_list(self.setup_file)\n self.assertIn(\"# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO\"\n \" - DO NOT EDIT\", setup_contents)\n\n def test_no_install_setup(self):\n setup_contents = _file_to_list(self.old_setup_file)\n self.assertNotIn(\n \"# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO\"\n \" - DO NOT EDIT\", setup_contents)\n\n def test_requirment_not_in_global(self):\n returncode = subprocess.call([sys.executable, \"update.py\",\n \"bad_project\"])\n self.assertEqual(returncode, 1)\n\n def test_requirment_not_in_global_non_fatal(self):\n env = os.environ.copy()\n env['NON_STANDARD_REQS'] = '1'\n returncode = subprocess.call(\n [sys.executable, \"update.py\", \"bad_project\"],\n env=env)\n self.assertEqual(returncode, 0)\n","sub_path":"tests/test_update.py","file_name":"test_update.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"558112041","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\nfrom io import StringIO\nfrom os.path import join\nfrom urllib.parse import quote\n\nimport diterator\nimport unicodecsv\nfrom hdx.location.currency import Currency\n\nfrom iati import checks\nfrom iati.activity import Activity\nfrom iati.calculatesplits import CalculateSplits\nfrom iati.lookups import Lookups\n\nlogger = logging.getLogger(__name__)\n\n\ndef retrieve_dportal(configuration, retriever, dportal_params, whattorun):\n \"\"\"\n Downloads activity data from D-Portal. Filters them and returns a\n list of activities.\n \"\"\"\n dportal_configuration = configuration['dportal']\n base_filename = dportal_configuration['filename']\n dportal_limit = dportal_configuration['limit']\n n = 0\n dont_exit = True\n while dont_exit:\n if dportal_params:\n params = dportal_params\n dont_exit = False\n else:\n offset = n * dportal_limit\n params = f'LIMIT {dportal_limit} OFFSET {offset}'\n logger.info(f'OFFSET {offset}')\n url = dportal_configuration['url'] % quote(dportal_configuration[f'{whattorun}_query'].format(params))\n filename = base_filename.format(n)\n text = retriever.retrieve_text(url, filename, 'D-Portal activities', False)\n if ' k - 1 else self.kthSmallest(\n root.right, k - count - 1)\n","sub_path":"LeetCode/230 Kth Smallest Element in a BST.py","file_name":"230 Kth Smallest Element in a BST.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"7467225","text":"import requests\nfrom bs4 import BeautifulSoup\n\nres = requests.get(\n \"https://list.tmall.com/search_product.htm?q=u%C5%CC&type=p&vmarket=&spm=875.7931836%2FB.a2227oh.d100&xl=U_1&from=mallfp..pc_1_suggest\")\n# print(res.text)\nsoup = BeautifulSoup(res.text, \"html.parser\")\nfor item in soup.select('.product-iWrap'):\n print(item.select('em')[0].text, item.select('.productShop-name')[0].text,\n item.select('.productStatus')[0].text.strip(), \"\\n\")\n","sub_path":"practice/tmall.py","file_name":"tmall.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"289898654","text":"\n\nimport numpy as np\n\nfrom typing import Union\nfrom gym.spaces import Box\n\nfrom actions import ActionStrategy, TradeActionUnion, DTypeString\nfrom trades import Trade, TradeType\n\n\nclass ContinuousActionStrategy(ActionStrategy):\n \"\"\"Simple continuous strategy, which calculates the trade amount as a fraction of the total balance.\"\"\"\n\n def __init__(self, instrument_symbol: str = 'BTC', max_allowed_slippage_percent: float = 1.0, dtype: DTypeString = np.float16):\n \"\"\"\n Arguments:\n instrument_symbol: The exchange symbol of the instrument being traded. Defaults to 'BTC'.\n max_allowed_slippage: The maximum amount above the current price the strategy will pay for an instrument. Defaults to 1.0 (i.e. 1%).\n dtype: A type or str corresponding to the dtype of the `action_space`. Defaults to `np.float16`.\n \"\"\"\n\n super().__init__(action_space=Box(0, 1, shape=(1, 1), dtype=dtype), dtype=dtype)\n\n self.instrument_symbol = instrument_symbol\n self.max_allowed_slippage_percent = max_allowed_slippage_percent\n\n def get_trade(self, action: TradeActionUnion) -> Trade:\n action_type, trade_amount = action\n trade_type = TradeType(int(action_type * len(TradeType)))\n\n current_price = self._exchange.current_price(symbol=self.instrument_symbol)\n base_precision = self._exchange.base_precision\n instrument_precision = self._exchange.instrument_precision\n\n amount = self._exchange.balance_of_instrument(self.instrument_symbol)\n price = current_price\n\n if trade_type is TradeType.MARKET_BUY or trade_type is TradeType.LIMIT_BUY:\n price_adjustment = 1 + (self.max_allowed_slippage_percent / 100)\n price = round(current_price * price_adjustment, base_precision)\n amount = round(self._exchange.balance * 0.99 * trade_amount / price, instrument_precision)\n\n elif trade_type is TradeType.MARKET_SELL or trade_type is TradeType.LIMIT_SELL:\n price_adjustment = 1 - (self.max_allowed_slippage_percent / 100)\n price = round(current_price * price_adjustment, base_precision)\n amount_held = self._exchange.portfolio.get(self.instrument_symbol, 0)\n amount = round(amount_held * trade_amount, instrument_precision)\n\n return Trade(self.instrument_symbol, trade_type, amount, price)\n","sub_path":"actions/continuous_action_strategy.py","file_name":"continuous_action_strategy.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"535313306","text":"# _*_ coding: utf-8 _*_\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport csv\r\nimport os\r\nimport time\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport numba\r\nimport itertools\r\n# =========== global parameters ===========\r\n\r\nT = 5 # iteration\r\nN = 2 # embedding_depth\r\nD = 8 # dimensional\r\nP = 64 # embedding_size\r\nB = 10 # mini-batch\r\nlr = 0.0001 # learning_rate\r\n# MAX_SIZE = 0 # record the max number of a function's block\r\nepochs = 100\r\nis_debug = True\r\n\r\ndata_folder=\"./features/\"\r\nmydata_folder=\"./data/\"\r\n# INDEX = mydata_folder + \"index_mydata.csv\"\r\nINDEX = data_folder + \"index.csv\"\r\nPREFIX = \"\"\r\n\r\ntest_file = os.path.join(mydata_folder, \"test\"+PREFIX+\".csv\")\r\n\r\nTEST_TFRECORD=\"data/TFrecord/test_gemini_data_\"+\"5430\"+PREFIX+\".tfrecord\"\r\n\r\nprint (TEST_TFRECORD)\r\n\r\n# ==================== load the function pairs list ===================\r\n# 1. load_dataset() load the pairs list for learning, which are\r\n# in train.csv, valid.csv, test.csv .\r\n# 1-1. load_csv_as_pair() process each csv file.\r\n# =====================================================================\r\ndef load_dataset():\r\n \"\"\" load the pairs list for training, testing, validing\r\n \"\"\"\r\n test_pair, test_label = load_csv_as_pair(test_file)\r\n\r\n return test_pair, test_label\r\n\r\ndef load_csv_as_pair(pair_label_file):\r\n \"\"\" load each csv file, which record the pairs list for learning and its label ( 1 or -1 )\r\n csv file : uid, uid, 1/-1 eg: 1.1.128, 1.4.789, -1\r\n pair_dict = {(uid, uid) : -1/1}\r\n \"\"\"\r\n pair_list = []\r\n label_list = []\r\n with open(pair_label_file, \"r\") as fp:\r\n pair_label = csv.reader(fp)\r\n for line in pair_label:\r\n pair_list.append([line[0], line[1]])\r\n label_list.append(int(line[2]))\r\n\r\n return pair_list, label_list\r\n\r\n\r\n# ====================== load block info and cfg ======================\r\n# 1. load_all_data() load the pairs list for learning, which are\r\n# in train.csv, valid.csv, test.csv .\r\n# 1-1. load_block_info()\r\n# 1-2. load_graph()\r\n# =====================================================================\r\ndef load_all_data():\r\n \"\"\" load all the real data, including blocks' featrue & functions' cfg using networkx\r\n uid_graph = {uid: nx_graph}\r\n feature_dict = {identifier : [[feature_vector]...]}, following the block orders\r\n \"\"\"\r\n uid_graph = {} #保存cfg图,id为版本号+基快地址\r\n feature_dict = {} #各个版本的所有block特征,id的版本号,值为block集合{基地址:特征}\r\n # read the direcory list and its ID\r\n # traversal each record to load every folder's data\r\n with open(INDEX, \"r\") as fp:\r\n for line in csv.reader(fp):\r\n # index.csv : folder name, identifier\r\n # eg: openssl-1.0.1a_gcc_4.6_dir, 1.1\r\n\r\n # load_block_info: save all the blocks' feature vector into feature_dict;\r\n # return current file's block number saved into block_num;\r\n # return each function's block id list saved into cur_func_block_dict.\r\n # 函数地址、 函数地址->函数调用地址\r\n block_num, cur_func_block_dict = load_block_info(os.path.join(data_folder, line[0], \"block_info.csv\"),\r\n feature_dict, line[1])\r\n\r\n if is_debug:\r\n print (\"load cfg ...\")\r\n # load every function's cfg\r\n load_graph(os.path.join(data_folder, line[0], \"adj_info.txt\"), block_num, cur_func_block_dict, line[1],\r\n uid_graph)\r\n\r\n return uid_graph, feature_dict\r\n\r\n\r\ndef load_my_data():\r\n \"\"\" load all the real data, including blocks' featrue & functions' cfg using networkx\r\n uid_graph = {uid: nx_graph}\r\n feature_dict = {identifier : [[feature_vector]...]}, following the block orders\r\n \"\"\"\r\n uid_graph = {} #保存cfg图,id为版本号+基快地址\r\n feature_dict = {} #各个版本的所有block特征,id的版本号,值为block集合{基地址:特征}\r\n # read the direcory list and its ID\r\n # traversal each record to load every folder's data\r\n\r\n # 函数地址、 函数地址->函数调用地址\r\n block_num, cur_func_block_dict = load_block_info(os.path.join(mydata_folder, \"block_info.csv\"), feature_dict , 'mydata')\r\n\r\n if is_debug:\r\n print (\"load cfg ...\")\r\n # load every function's cfg\r\n load_graph(os.path.join(mydata_folder, \"adj_info.txt\"), block_num, cur_func_block_dict,'mydata',\r\n uid_graph)\r\n\r\n return uid_graph, feature_dict\r\n\r\n\r\ndef load_block_info(feature_file, feature_dict, uid_prefix):\r\n \"\"\" load all the blocks' feature vector into feature dictionary.\r\n the two returned values are for next step, loading graph.\r\n return the block numbers —— using to add the single node of the graph\r\n return cur_func_blocks_dict —— using to generate every function's cfg(subgraph)\r\n \"\"\"\r\n feature_dict[str(uid_prefix)] = []#版本号:特征矩阵\r\n cur_func_blocks_dict = {}#函数地址->函数调用地址\r\n\r\n block_uuid = []#函数地址\r\n line_num = 0\r\n block_feature_dic = {}#函数地址:[特征矩阵(指令数量)]\r\n with open(feature_file, \"r\") as fp:\r\n if is_debug:\r\n print (feature_file)\r\n for line in csv.reader(fp):\r\n line_num += 1\r\n # skip the topic line\r\n #if line_num == 1:\r\n # continue\r\n if line[0] == \"\":\r\n continue\r\n block_uuid.append(str(line[0]))\r\n # read every bolck's features\r\n block_feature = [float(x) for x in (line[4:13])]\r\n del block_feature[6]\r\n block_feature_dic.setdefault(str(line[0]),block_feature)\r\n\r\n # record each function's block id.\r\n # for next step to generate the control flow graph\r\n # so the root block need be add.\r\n if str(line[2].strip()) not in cur_func_blocks_dict:\r\n cur_func_blocks_dict[str(line[2].strip())] = [str(line[0])]\r\n else:\r\n cur_func_blocks_dict[str(line[2].strip())].append(str(line[0]))\r\n feature_dict[str(uid_prefix)].append(block_feature_dic)\r\n\r\n return block_uuid, cur_func_blocks_dict\r\n\r\n\r\n\r\n#@numba.jit\r\ndef load_graph(graph_file, block_number, cur_func_blocks_dict, uid_prefix, uid_graph):\r\n \"\"\" load all the graph as networkx\r\n \"\"\"\r\n graph = nx.read_edgelist(graph_file, create_using=nx.DiGraph(), nodetype=str)\r\n\r\n # add the missing vertexs which are not in edge_list\r\n for i in block_number:\r\n if i not in graph.nodes():\r\n graph.add_node(i)\r\n\r\n for func_id in cur_func_blocks_dict:\r\n graph_sub = graph.subgraph(cur_func_blocks_dict[func_id])\r\n uid = uid_prefix + \".\" + str(func_id)\r\n uid_graph[uid] = graph_sub\r\n # -----------------------可视化cfg图----------------------\r\n # print('输出网络中的节点...')\r\n # print(graph_sub.nodes())\r\n # print('输出网络中的边...')\r\n # print(graph_sub.edges())\r\n # print('输出网络中边的数目...')\r\n # print(graph_sub.number_of_edges())\r\n # print('输出网络中节点的数目...')\r\n # print(graph_sub.number_of_nodes())\r\n # print('给网路设置布局...')\r\n # pos = nx.shell_layout(graph_sub)\r\n # nx.draw(graph_sub, pos, with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5)\r\n # plt.show()\r\n\r\n\r\n#@numba.jit\r\ndef construct_learning_dataset(uid_pair_list):\r\n \"\"\" Construct pairs dataset to train the model.\r\n attributes:\r\n adj_matrix_all store each pairs functions' graph info, (i,j)=1 present i--》j, others (i,j)=0\r\n features_all store each pairs functions' feature map\r\n \"\"\"\r\n print (\" start generate adj matrix pairs...\")\r\n adj_matrix_all_1, adj_matrix_all_2 = generate_adj_matrix_pairs(uid_pair_list)\r\n\r\n print (\" start generate features pairs...\")\r\n ### !!! record the max number of a function's block\r\n features_all_1, features_all_2, max_size, num1, num2 = generate_features_pair(uid_pair_list)\r\n\r\n return adj_matrix_all_1, adj_matrix_all_2, features_all_1, features_all_2, num1, num2, max_size\r\n\r\n\r\n#@numba.jit\r\ndef generate_adj_matrix_pairs(uid_pair_list):\r\n \"\"\" construct all the function pairs' cfg matrix.\r\n \"\"\"\r\n adj_matrix_all_1 = []\r\n adj_matrix_all_2 = []\r\n # traversal all the pairs\r\n count = 0\r\n for uid_pair in uid_pair_list:\r\n if is_debug:\r\n count += 1\r\n print (\" %04d martix, [ %s , %s ]\"%(count, uid_pair[0], uid_pair[1]))\r\n adj_matrix_pair = []\r\n # each pair process two function\r\n key_0= 'mydata' + \".\" + str(uid_pair[0])\r\n for eachKey in uid_graph_1.keys():\r\n print(eachKey)\r\n graph = uid_graph_1[key_0]\r\n\r\n # pos = nx.shell_layout(graph)\r\n # nx.draw(graph, pos, with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5)\r\n # plt.show()\r\n # origion_adj_1 = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n # origion_adj_1.resize(size, size, refcheck=False)\r\n # adj_matrix_all_1.append(origion_adj_1.tolist())\r\n adj_arr = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n adj_str = adj_arr.astype(np.string_)\r\n #扁平化列表\r\n adj_matrix_all_1.append(\",\".join(list(itertools.chain.from_iterable(adj_str))))\r\n\r\n select_list = uid_pair[1].split('.')\r\n if (len(select_list) >= 2):\r\n graph = uid_graph[uid_pair[1]] #解决标签为1的情况\r\n else:\r\n key_1 = \"mydata\" + \".\" + uid_pair[1] #标签为-1的情况\r\n graph = uid_graph_1[key_1]\r\n # origion_adj_2 = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n # origion_adj_2.resize(size, size, refcheck=False)\r\n # adj_matrix_all_2.append(origion_adj_2.tolist())\r\n adj_arr = np.array(nx.convert_matrix.to_numpy_matrix(graph, dtype=float))\r\n adj_str = adj_arr.astype(np.string_)\r\n adj_matrix_all_2.append(\",\".join(list(itertools.chain.from_iterable(adj_str))))\r\n\r\n return adj_matrix_all_1, adj_matrix_all_2\r\n\r\n\r\n#@numba.jit\r\ndef convert_graph_to_adj_matrix(graph):\r\n \"\"\" convert the control flow graph as networkx to a adj matrix (v_num * v_num).\r\n 1 present an edge; 0 present no edge\r\n \"\"\"\r\n node_list = graph.nodes()\r\n adj_matrix = []\r\n\r\n # get all the block id in the cfg\r\n # construct a v_num * v_num adj martix\r\n for u in node_list:\r\n # traversal each block's edgd list,to add the\r\n u_n = graph.neighbors(u)\r\n neighbors = []\r\n for tmp in u_n:\r\n neighbors.append(tmp)\r\n node_adj = []\r\n for v in node_list:\r\n if v in neighbors:\r\n node_adj.append(1)\r\n else:\r\n node_adj.append(0)\r\n adj_matrix.append(node_adj)\r\n # print adj_matrix\r\n return adj_matrix\r\n\r\n\r\n#@numba.jit\r\ndef generate_features_pair(uid_pair_list):\r\n \"\"\" Construct each function pairs' block feature map.\r\n \"\"\"\r\n node_vector_all_1 = []\r\n node_vector_all_2 = []\r\n num1 = []\r\n num2 = []\r\n node_length = []\r\n # traversal all the pairs\r\n count = 0\r\n for uid_pair in uid_pair_list:\r\n if is_debug:\r\n count += 1\r\n print (\" %04d feature, [ %s , %s ]\"%(count, uid_pair[0], uid_pair[1]))\r\n node_vector_pair = []\r\n # each pair process two function\r\n uid = 'mydata' + \".\" + str(uid_pair[0])\r\n\r\n node_list = uid_graph_1[uid].nodes()\r\n uid_prefix = uid.rsplit('.', 1)[0] # 从右边第一个'.'分界,分成两个字符串 即 identifier, function_id\r\n node_vector = []\r\n for node in node_list:\r\n node_vector.append(feature_dict_1[str(uid_prefix)][0][node])\r\n node_length.append(len(node_vector))\r\n num1.append(len(node_vector))\r\n node_arr = np.array(node_vector)\r\n node_str = node_arr.astype(np.string_)\r\n node_vector_all_1.append(\",\".join(list(itertools.chain.from_iterable(node_str))))\r\n\r\n select_list = uid_pair[1].split('.')\r\n node_vector = []\r\n if (len(select_list) >= 2):\r\n uid = uid_pair[1]\r\n node_list = uid_graph[uid].nodes()\r\n uid_prefix = uid.rsplit('.', 1)[0]\r\n for node in node_list:\r\n node_vector.append(feature_dict[str(uid_prefix)][0][node])\r\n else:\r\n uid = \"mydata\" + \".\" + uid_pair[1] #标签为-1的情况\r\n node_list = uid_graph_1[uid].nodes()\r\n uid_prefix = uid.rsplit('.', 1)[0] # 从右边第一个'.'分界,分成两个字符串 即 identifier, function_id\r\n for node in node_list:\r\n node_vector.append(feature_dict_1[str(uid_prefix)][0][node])\r\n node_length.append(len(node_vector))\r\n num2.append(len(node_vector))\r\n node_arr = np.array(node_vector)\r\n node_str = node_arr.astype(np.string_)\r\n node_vector_all_2.append(\",\".join(list(itertools.chain.from_iterable(node_str))))\r\n\r\n num1_re = np.array(num1)\r\n num2_re = np.array(num2)\r\n #num1_re = num1_arr.astype(np.string_)\r\n #num2_re = num2_arr.astype(np.string_)\r\n #(100000)(100000)()(100000,)(100000,)\r\n return node_vector_all_1, node_vector_all_2, np.max(node_length),num1_re,num2_re\r\n\r\n # =============== convert the real data to training data ==============\r\n # 1. construct_learning_dataset() combine the dataset list & real data\r\n # 1-1. generate_adj_matrix_pairs() traversal list and construct all the matrixs\r\n # 1-1-1. convert_graph_to_adj_matrix() process each cfg\r\n # 1-2. generate_features_pair() traversal list and construct all functions' feature map\r\n # =====================================================================\r\n \"\"\" Parameter P = 64, D = 8, T = 7, N = 2, B = 10\r\n X_v = D * 1 <---> 8 * v_num * 10\r\n W_1 = P * D <---> 64* 8 W_1 * X_v = 64*1\r\n mu_0 = P * 1 <---> 64* 1\r\n P_1 = P * P <---> 64*64\r\n P_2 = P * P <---> 64*64\r\n mu_2/3/4/5 = P * P <---> 64*1\r\n W_2 = P * P <---> 64*64\r\n \"\"\"\r\n\r\n\r\n\r\n# ========================== the main function ========================\r\n# 1. load_dataset() load the train, valid, test csv file.\r\n# 2. load_all_data() load the origion data, including block info, cfg by networkx.\r\n# 3. construct_learning_dataset() combine the csv file and real data, construct training dataset.\r\n# =====================================================================\r\n# 1. load the train, valid, test csv file.\r\ndata_time = time.time()\r\ntest_pair, test_label = load_dataset()\r\nprint (\"1. loading pairs list time\", time.time() - data_time, \"(s)\")\r\n\r\n# 2. load the origion data, including block info, cfg by networkx.\r\ngraph_time = time.time()\r\nuid_graph_1, feature_dict_1 = load_my_data()\r\nuid_graph, feature_dict = load_all_data()\r\nprint (\"2. loading graph data time\", time.time() - graph_time, \"(s)\")\r\n\r\n# 3. construct training dataset.\r\ncons_time = time.time()\r\n\r\n\r\n# ========================== clean memory ========================\r\n# del train_pair, train_adj_matrix_1,train_adj_matrix_2,train_feature_map_1,train_feature_map_2,train_max\r\n\r\n# ========================== clean memory ========================\r\n# del valid_pair, valid_adj_matrix_1,valid_adj_matrix_2,valid_feature_map_1,valid_feature_map_2,valid_max\r\n\r\n# ======================= construct test data =====================\r\ntest_adj_matrix_1, test_adj_matrix_2, test_feature_map_1, test_feature_map_2,test_num1, test_num2, test_max \\\r\n = construct_learning_dataset(test_pair)\r\n# ========================== store in pickle ========================\r\nnode_list = np.linspace(test_max,test_max, len(test_label),dtype=int)\r\nwriter = tf.python_io.TFRecordWriter(TEST_TFRECORD)\r\nfor item1,item2,item3,item4,item5,item6, item7, item8 in itertools.izip(\r\n test_label, test_adj_matrix_1, test_adj_matrix_2, test_feature_map_1, test_feature_map_2,\r\n test_num1, test_num2, node_list):\r\n example = tf.train.Example(\r\n features = tf.train.Features(\r\n feature = {\r\n 'label':tf.train.Feature(int64_list = tf.train.Int64List(value=[item1])),\r\n 'adj_matrix_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item2])),\r\n 'adj_matrix_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item3])),\r\n 'feature_map_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item4])),\r\n 'feature_map_2': tf.train.Feature(bytes_list=tf.train.BytesList(value=[item5])),\r\n 'num1':tf.train.Feature(int64_list = tf.train.Int64List(value=[item6])),\r\n 'num2':tf.train.Feature(int64_list = tf.train.Int64List(value=[item7])),\r\n 'max': tf.train.Feature(int64_list=tf.train.Int64List(value=[item8]))}))\r\n serialized = example.SerializeToString()\r\n writer.write(serialized)\r\nwriter.close()\r\n","sub_path":"py/toTFrecord_mydata.py","file_name":"toTFrecord_mydata.py","file_ext":"py","file_size_in_byte":17465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"202983047","text":"# -*- coding: utf-8 -*-\n# @Author : Jing\n# @FileName: 108. Convert Sorted Array to Binary Search Tree.py\n# @IDE: PyCharm\n# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/\nfrom base import TreeNode, PrintTree\n\n\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n if not nums:\n return None\n mid = (len(nums)-1) >> 1\n root = TreeNode(nums[mid])\n root.left = self.sortedArrayToBST(nums[:mid])\n root.right = self.sortedArrayToBST(nums[mid+1:])\n return root\n\n\nif __name__ == '__main__':\n nums = [-10, -3, 0, 5, 9]\n s = Solution()\n root = s.sortedArrayToBST(nums)\n p = PrintTree()\n p.in_order(root)\n p.print_tree()\n","sub_path":"Tree/108. Convert Sorted Array to Binary Search Tree.py","file_name":"108. Convert Sorted Array to Binary Search Tree.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"443845995","text":"# Kata 4th Kyu \"Square into Squares. Protect trees!\" \r\n# https://www.codewars.com/kata/54eb33e5bc1a25440d000891\r\n\r\ndef decompose (n):\r\n objetivo=0\r\n #Defino un valor objetivo que es el que voy a reducir\r\n resultado=[n]\r\n #Genero un vector resultado\r\n while resultado:\r\n actual=resultado.pop(-1)\r\n #Obtengo el último valor de resultado como \"actual\". En principio va a ser el número ingresado.\r\n objetivo+=actual**2\r\n #defino al objetivo como el cuadrado de \"actual\" es decir el número que debería anular\r\n for i in range (actual-1,0,-1):\r\n #defino una lista que va entre el valor que ingresé menos 1 y cero, yendo del mayor al menor.\r\n if objetivo-(i**2)>=0:\r\n #si la resta entre el valor al que tengo que llegar y el propuesto es mayor a cero (es decir si es factible) avanzo y agrego al número.\r\n resultado.append(i)\r\n objetivo-=i**2\r\n if objetivo==0:\r\n resultado.sort()\r\n #Si el resto es cero, ordeno los resultados y lo devuelvo.\r\n return (resultado)\r\n #Si no se cumplen las condiciones anteriores se sigue con el while, restándole 1 al último número que no funcionó.\r\n ","sub_path":"4th Kyu/Square into Squares. Protect trees!.py","file_name":"Square into Squares. Protect trees!.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"198897854","text":"# slicer imports\nfrom __main__ import vtk, slicer\n\n# python includes\nimport sys\nimport time\n\nclass Helper(object):\n\n @staticmethod\n def ConvertRAStoIJK(volumeNode,rasCoordinates):\n '''\n '''\n rasToIjkMatrix = vtk.vtkMatrix4x4()\n volumeNode.GetRASToIJKMatrix(rasToIjkMatrix)\n\n # the RAS coordinates need to be 4\n if len(rasCoordinates) < 4:\n rasCoordinates.append(1)\n\n ijkCoordinates = rasToIjkMatrix.MultiplyPoint(rasCoordinates)\n\n return ijkCoordinates\n","sub_path":"PythonModules/SlicerVmtkCommonLib/Helper.py","file_name":"Helper.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"400906604","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 22 12:28:00 2020\n\n@author: marco\n\"\"\"\nnumbers = [\n [34, 63, 88, 71, 29],\n [90, 78, 51, 27, 45],\n [63, 37, 85, 46, 22],\n [51, 22, 34, 11, 18]\n ]\n\nmean = lambda x : sum(x)/len(x)\n#def mean(num_list):\n# return sum(num_list) / len(num_list)\n\naverages = list(map(mean, numbers))\nprint(averages)\n","sub_path":"22_06_20_lambda_functions.py","file_name":"22_06_20_lambda_functions.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"327741072","text":"import math\nimport sys\nimport numpy as np\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\nimport convexset as conv\nfrom convexset import Square\nimport time\nimport numba\nfrom numba import jit\nfrom numba import jitclass\n\nclass RRTreeBasis:\n r_expand = 0.2\n r_eps = 0.5\n def __init__(self, X, x_init, x_goal, obstacle):\n self.ndim = x_init.shape[0]\n self.x_goal = x_goal\n self.obs_set = obstacle\n self.X = X\n self.G = {'node': x_init, 'parent': [0]}# a decent tree structure is not necessary\n self.randInX = lambda N:X.min_bound + np.random.rand(2, N)*np.asarray(X.max_bound-X.min_bound)\n #self.randInU = lambda N:U.min_bound + np.random.rand(2, N)*np.asarray(U.max_bound-U.min_bound)\n\n def show_obstacles(self):\n self.X.show_convex(lcolor = 'b')\n for obs in self.obs_set:\n obs.show_convex(lcolor = 'r')\n\n def show_tree(self):\n global idx\n pos = self.G['node']\n idx = self.G['parent']\n for i in range(len(idx)):\n plt.plot([pos[0, i], pos[0, idx[i]]], [pos[1, i], pos[1, idx[i]]], 'go')\n plt.plot([pos[0, i], pos[0, idx[i]]], [pos[1, i], pos[1, idx[i]]], 'k-')\n\n def _sample(self):\n while(True):\n x_rand = self.randInX(1)\n logic = any(self._isCollide(x_rand))\n if logic==False:\n break\n return x_rand\n\n def _nearest(self, G, x_querry):\n dist_set = np.linalg.norm(G['node'] - x_querry, axis=0)\n return np.argmin(dist_set)\n\n def _near(self, G, x_pivot, r):\n dist_pivot = np.linalg.norm(G['node'] - x_pivot, axis=0)\n return np.nonzero(dist_pivot Episode 2 > Episode 3.\n\n# ## How many respondents have actually watched all the films?\n\n# In[5]:\n\n\nseen_list = [col for col in star_wars.columns if \"seen_\" in col]\n#print(seen_list)\n#star_wars[seen_list]\nseen_count_graph = star_wars[seen_list].sum().plot.bar(rot=0)\nclean_graph(seen_count_graph,title=\"Movies watched by respondents\",x_label=\"Episode\",y_label=\"Count\",remove_spines=True)\nseen_count_graph.set_xticklabels([1,2,3,4,5,6])\nplt.show()\n\n\n# In[6]:\n\n\nseen_sum = star_wars[seen_list].sum().reset_index()\nrank_mean = star_wars[rank_list].mean().reset_index()\nrank_mean\ncorrelation = pd.concat([seen_sum.iloc[:,1],rank_mean.iloc[:,1]],ignore_index=True,axis=1)\n#corrolation = \n#corr = pd.merge([seen_sum,rank_mean],axis=1)\n#corr['seen'] = \n#corr['seen'] = seen_sum\ncorrelation.rename(index={0:'Episode_1',\n 1:'Episode_2',\n 2:'Episode_3',\n 3:'Episode_4',\n 4:'Episode_5',\n 5:'Episode_6',},\n columns={0:\"seen\",\n 1:\"ranking\"}\n ,inplace=True)\nclean_graph(correlation.plot.scatter('seen','ranking'),\n title=\"A not very interesting graph for quick identification of points\",\n remove_spines=True)\nplt.show()\ncorrelation\n#fig.text(.5, .05, txt, ha='center')\n\n\n# More respondents had seen *Empire* and *Jedi* than any other films, so there may be some bias in this dataset. In general, th more people that had seen a film, the higher the ranking. This makes sense, since a respondent can only rank a film that they've seen. The exception is *Episode 1: The Phantom Menace*, which, depsite having been watched by more people than *Episode 4: A New Hope*, was ranked lower. This follows from our earlier observation that the prequils ranked lower than the origional series.\n\n# ## Demographics\n# There are a few ways we can divide the dataset to see how different people rate the movies. Three ways we can do this are ny looking at \n# \n# * Self-described Star Wars fans vs. non-fans;\n# * Trekkies vs. non-Trekkies;\n# * Men vs. women.\n# \n# We'll need to do a bit of cleaning first. First thing is to sort out the titles of these columns. Next, all three fields include null-values; we don't want to drop these from the dataset, since, for example, the ratings by Star Wars fans isn't voided by not knowing their sex or if they're also Trekkies. What will becoome the `Trekkie` column also needs the `Yes/No` values to be converted using the `to_bool` function above.\n\n# In[7]:\n\n\nstar_wars.rename(columns={\"Do you consider yourself to be a fan of the Star Wars film franchise?\": \"fan\",\n \"Do you consider yourself to be a fan of the Star Trek franchise?\": \"Trekkie\"},\n inplace=True)\nstar_wars['Trekkie'] = star_wars['Trekkie'].map(to_bool)\n\n\n# Before we get started, let's be super lazy and convert the code for the above into functions so that we don't have to type out the whole analysis each time:\n\n# In[8]:\n\n\ndef construct_rankings(respondents,subset):\n fig = plt.figure(figsize=(9,6))\n mean_ranking = fig.add_subplot(1,2,1)\n empire_ranking = fig.add_subplot(1,2,2)\n\n bar_positions = np.arange(6) + 1\n bar_heights = respondents[rank_list].mean().values\n mean_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color='red',label=subset)\n \n bar_heights = star_wars[rank_list].mean().values\n mean_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color='blue',label=\"combined\")\n \n mean_ranking.set_xlim(0,6.5)\n clean_graph(mean_ranking,title=\"Film ratings\",x_label=\"Episode\",y_label=\"Rank\",remove_spines=True)\n mean_ranking.set_ylim(0.5,6)\n #mean_ranking.legend()\n \n bar_positions = np.arange(6) + 1\n bar_heights = respondents['rank_episode_5'].value_counts()/respondents.shape[0]\n empire_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color=\"red\",label=subset)\n \n bar_heights = star_wars['rank_episode_5'].value_counts()/star_wars.shape[0]\n empire_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color=\"blue\",label=\"combined\")\n \n empire_ranking.set_xlim(0.5,6.5)\n clean_graph(empire_ranking,title=\"Empire Ranking\",x_label=\"Rank\",y_label=\"Proportional Rank\",remove_spines=True)\n empire_ranking.legend()\n plt.show()\n\ndef construct_viewings(respondents, subset):\n seen_prop = respondents[seen_list].sum()/respondents.shape[0]\n all_prop = star_wars[seen_list].sum()/star_wars.shape[0]\n seen_count_graph = seen_prop.plot.bar(rot=0,width=-0.4,align='edge',color=\"red\",label=subset)\n seen_count_graph = all_prop.plot.bar(rot=0,width=0.4,align='edge',color=\"blue\",label=\"combined\")\n clean_graph(seen_count_graph,\n title=\"Movies watched by {}\".format(subset),\n x_label=\"Episode\",\n y_label=\"Watched by proportion\",\n remove_spines=True)\n seen_count_graph.set_xticklabels([1,2,3,4,5,6])\n seen_count_graph.set_xlim(-0.5,6.5)\n seen_count_graph.set_ylim(0,1)\n #seen_count_graph.legend()\n plt.show()\n \n\n\n# ### Self-proclaimed Star Wars fans\n\n# In[9]:\n\n\nprint('Constructing the fan-only dataframe....')\nfans = star_wars[star_wars['fan']==True]\nprint('Shape of dataframe:', fans.shape)\nprint('checking for missing values...')\nprint(fans[rank_list].count()) #the only null vlaue is one \nprint('One missing value in `rank_episode_1`')\n\nprint('Checking for ratings by non-fans in the main dataframe....')\n\nmask = (star_wars['fan']==False) & (star_wars['rank_episode_5'].notna())\nprint('Number of non-fans who ranked films:', star_wars[mask].shape[0])\n#construct_graphs(fans)\n\n\n# By looking at subsets of the main `star_wars` dataframe, we can see that:\n# \n# * All Star Wars fans ranked all movies, except for one missing value for *Episode 1: The Phantom Menace*;\n# * There were no non-fans who actually submitted rankings.\n# \n# Breaking the respondents down along fanship of the franchise doesn't tell us anything: since there's no data for non-fans, we can't draw any conclusions for them, and the fan-rankings are the same as for the database as a whole.\n\n# ### Trekkies\n# \n# Well, that was dissapointing. But to be fair, why would non-fans bother to fill in the survey? Let's look at Trekkies vs. philistines.\n\n# In[10]:\n\n\ntrekkies = star_wars[star_wars['Trekkie']==True]\nconstruct_rankings(trekkies,\"Trekkies\")\n\n\n# The Trekkies rankings were conistant with the overall average, however, the Trekkies ranked `Empire` slightly higher than the general response. Note that the graph on the right gives the proportion of respondents who ranked the films.\n# \n\n# In[11]:\n\n\nconstruct_viewings(trekkies,\"Trekkies\")\n\n\n# Trekies are slightly more likely than the general population to have seen Star Wars films (by about 5%). Is it true to say that if you're a Star Wars fan then you're also likely to be a Trekkie?\n\n# In[12]:\n\n\nstar_trekkies = star_wars[(star_wars['fan']==True) & (star_wars['Trekkie']==True)]\nprint('Number of Star Wars fans:',fans.shape[0])\nprint('Number of Star Trek fans:',trekkies.shape[0])\nprint('There are {} more Trekkies than Star Wars fans in the dataset'.format(trekkies.shape[0]-fans.shape[0]))\n\nconstruct_rankings(star_trekkies,\"fans of both\")\n\n\n# ### Male vs female rankings\n# One more dempgraphic breakdown which we can look at is the divide along gender lines.\n\n# In[13]:\n\n\nmale = star_wars[star_wars['Gender']=='Male']\nfemale = star_wars[star_wars['Gender']=='Female']\n\nmale_fans = male[male['fan']==True]\nfemale_fans = female[female['fan']==True]\n\nprint('Male fans: {}/{} total'.format(male_fans.shape[0],male.shape[0]))\nprint('Female fans: {}/{} total'.format(female_fans.shape[0],female.shape[0]))\n\n\n# So while more females responded to the survey, the absolute number of males who describe themselves as a Star Wars fan is higher.\n\n# In[14]:\n\n\nconstruct_rankings(male,\"Male respondents\")\nconstruct_rankings(female,\"Female respondents\")\n\n\n# There are some rather unexpected results here. Male respondents ranked *Episode 1* and *Episode 2* slightly lower than the average, and ranked the others slightly higher. About 1/3 men ranked *Empire* as being the best film, while only about 1/4 of the total did so. Conversely, female respondents ranked the *Episode 1* and *Episode 2* slightly higher, and the other films slightly lower than the total. Since there were more male than female respondents, the combined rankings more accurately reflect the opinions of the men. Let's put the male and female rankings on the same axes for easier comparison:\n\n# In[28]:\n\n\nfig = plt.figure(figsize=(9,6))\nmean_ranking = fig.add_subplot(1,2,1)\nempire_ranking = fig.add_subplot(1,2,2)\n\nbar_positions = np.arange(6) + 1\nbar_heights = male[rank_list].mean().values\nmean_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color='red',label=\"Male\")\n\nbar_heights = female[rank_list].mean().values\nmean_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color='blue',label=\"Female\")\n\nmean_ranking.set_xlim(0,6.5)\nclean_graph(mean_ranking,title=\"Film ratings\",x_label=\"Episode\",y_label=\"Rank\",remove_spines=True)\nmean_ranking.set_ylim(0.5,6)\n \nbar_positions = np.arange(6) + 1\nbar_heights = male['rank_episode_5'].value_counts()/male.shape[0]\nempire_ranking.bar(bar_positions,bar_heights,width=-0.4,align='edge',color=\"red\",label=\"Male\")\n \nbar_heights = female['rank_episode_5'].value_counts()/female.shape[0]\nempire_ranking.bar(bar_positions,bar_heights,width=0.4,align='edge',color=\"blue\",label=\"Female\")\n \nempire_ranking.set_xlim(0.5,6.5)\nclean_graph(empire_ranking,title=\"Empire Ranking\",x_label=\"Rank\",y_label=\"Proportional Rank\",remove_spines=True)\nempire_ranking.legend()\nplt.show()\n\n\n# While female respondents were less polarised in their ranking choice, both sexes agree on the ranking of the films. But who's seen more films?\n\n# In[16]:\n\n\nconstruct_viewings(male,\"Male respondents\")\nconstruct_viewings(female,\"Female respondents\")\n\n\n# Male respondents were significantly more likely to have seen the *Star Wars* films than the total population, while female respondents were less likely to have watched them. Comparing the two directly:\n\n# In[17]:\n\n\nmale_prop = male[seen_list].sum()/male.shape[0]\nfemale_prop = female[seen_list].sum()/female.shape[0]\nseen_count_graph = male_prop.plot.bar(rot=0,width=-0.4,align='edge',color=\"red\",label=\"Male\")\nseen_count_graph = female_prop.plot.bar(rot=0,width=0.4,align='edge',color=\"blue\",label=\"Female\")\nclean_graph(seen_count_graph,\n title=\"Movies watched by {}\".format(\"Men and Women\"),\n x_label=\"Episode\",\n y_label=\"Watched by proportion\",\n remove_spines=True)\nseen_count_graph.set_xticklabels([1,2,3,4,5,6])\nseen_count_graph.set_xlim(-0.5,6.5)\nseen_count_graph.set_ylim(0,1)\nseen_count_graph.legend()\nplt.show()\n\n\n# Male respondents were much more likely to have watched each *Star Wars* film than female respondents--a difference of about 20%.\n\n# ## Who shot first?\n# Now let's look at something truely controvertial: who shot first? \n# An early scene in *Star Wars Episode 4: A New Hope* shows Han Solo meeting with a bounty Hunter named Greedo in a Canteena on Tatooine. In the origional release, Han shoots Greedo. In the '90s rerelease, the scene was edited to make Greedo shoot first, and for Han to fire back in self-defence. See [this Wikipedia article](https://en.wikipedia.org/wiki/Han_shot_first) on the subject.\n# \n# **Prediction:** it depends on which release of *Episode 4: A New Hope* the respondents saw first: the origional release from the '70s, or the '90s remaster. It's therefore worth including the `Age` of the respondents in the analysis. We'll first have to clean these columns up a bit.\n\n# In[18]:\n\n\n# for col in star_wars.columns:\n# print( col)\nHan_Greedo = star_wars[['Which character shot first?','Age']].copy()\nHan_Greedo.rename(columns={'Which character shot first?': 'shot_first','Age': 'age'},inplace=True)\n\n#take a look at the data and drop null values\nprint(Han_Greedo['shot_first'].value_counts(dropna=False))\nprint()\nprint(Han_Greedo['age'].value_counts(dropna=False))\nprint()\nold_size = Han_Greedo.shape[0]\nprint(\"Size before drop:\", old_size)\nHan_Greedo.dropna(how=\"any\",inplace=True)\nnew_size = Han_Greedo.shape[0]\nprint(\"Size after drop: {}----{} removed\".format(new_size,old_size-new_size))\n\n\n# In[19]:\n\n\ndef age_groups(age):\n if age == \"18-29\": return 1\n elif age == \"30-44\": return 2\n elif age == \"45-60\": return 3\n elif age == \"> 60\": return 4\n \n \nHan_Greedo['age'] = Han_Greedo['age'].map(age_groups)\n\n\n# In[20]:\n\n\nclean_graph(Han_Greedo['shot_first'].value_counts().plot.bar(rot=0),\n title=\"Who shot first?\",\n y_label=\"Count\",\n remove_spines=True)\nplt.show()\nHan_Greedo['shot_first'].value_counts()\n\n\n# Of the respondents who understood the question, most said that Han shot first (322 vs. 193). 37% of respondents didn't understand the question, 39% said Han shot first, and 23% said Greedo shot first. The rest didn't submit an answer. How does this break down by age?\n\n# In[114]:\n\n\nfig = plt.figure(figsize=(9,6))\n# Han = fig.add_subplot(1,3,1)\n# Greedo = fig.add_subplot(1,3,2)\n# dunno = fig.add_subplot(1,3,3)\ni=1\nfor answer in [\"Han\",\"Greedo\",\"I don't understand this question\"]:\n ax = fig.add_subplot(1,3,i)\n bar_positions = np.arange(4)# + 1\n bar_heights = Han_Greedo[Han_Greedo['shot_first']==answer]['age'].value_counts(sort=False)/ Han_Greedo['age'].value_counts(sort=False)\n ax.bar(bar_positions,bar_heights,width=0.4,align='center')\n if answer == \"Han\": title=\"Han shot first\"\n if answer == \"Greedo\": title=\"Greedo shot first\"\n if answer == \"I don't understand this question\": title=\"Don't know\"\n clean_graph(ax,title=title,remove_spines=True)\n ax.set_xticks(range(0,4))\n ax.set_ylim(0,0.6)\n ax.set_xticklabels([\"18-29\",\"30-44\",\"45-60\",\">61\"])\n i += 1\n\n\n# Contrary to expectations, it seems like the younger a respndent was, the more likely they were to say that Han shot first, while the only group that said that Greedo shot first was the 30-44 cohort. This latter observation makes some sense, since most members of this group would have grown up knowing the '90s remastered edition. The former observation is a little more eseorteric in its explaination. The phrase \"Han shot first\" is something of an internet meme; and therefore something that younger audiences are more likely to pick up on. See [this page](https://knowyourmeme.com/memes/han-shot-first) for details. \n# Respondents in the over 61 group were by far the most likely to not understand the question. \n","sub_path":"Star_Wars_Survey/Star_wars.py","file_name":"Star_wars.py","file_ext":"py","file_size_in_byte":18526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"253310455","text":"# -*- coding: utf-8 -*-\nimport Tkinter\nimport tkFileDialog\nimport xlrd\nimport os.path\nimport numpy as np\nimport xlsxwriter\nfrom xlsxwriter.utility import xl_rowcol_to_cell, xl_range_abs\n\n# ファイル選択画面の作成\nroot = Tkinter.Tk()\nroot.title(u\"小テスト得点集計プログラム\")\nroot.geometry(\"500x300\")\n\n# 選択ファイルのファイル形式とパス\nfTyp=[('Excelファイル(複数選択可)','.xlsx')]\niDir='c:/'\n\n# 解答のファイルを取得する関数\ndef DeleteEntryValue1(event):\n\tEditBox1.delete('1.0', 'end')\n\tanspath = tkFileDialog.askopenfilenames(filetypes=fTyp,initialdir=iDir)\n\tglobal anslist\n\tanslist = [[['0' for col in range(22)] for row in range(200)] for row in range(14)]\n\tglobal count\n\tcount = 0\n\t#複数ファイル(.xlsx)から読み取ったデータを3次元配列に格納\n\tfor path in anspath:\n\t\tReader = xlrd.open_workbook(path)\n\t\tsheet_1 = Reader.sheet_by_index(0)\n\t\tfor row in range(sheet_1.nrows):\n\t\t\tfor col in range(sheet_1.ncols):\n\t\t\t\tanslist[count][row][col] = sheet_1.cell(row,col).value\n\t\tfname = os.path.basename(path)\n\t\tglobal outfname\n\t\toutfname, ext = os.path.splitext(fname)\n\t\toutfname = outfname[0:4]\n\t\tEditBox1.insert(Tkinter.END,fname+\"\\n\")\n\t\tcount += 1\n\tEditBox1.insert(Tkinter.END,\"ファイル数:\"+str(count))\n\n# 終了\ndef ChangeText1(event):\n\troot.quit()\n\n# ファイル選択画面のテキストボックスとボタンの生成\nEditBox1 = Tkinter.Text(height=16,width=50)\nEditBox1.insert(Tkinter.END,\"各講義の採点結果ファイル\")\nEditBox1.pack()\nButton1 = Tkinter.Button(text = u'各講義の採点結果ファイルをすべて選んでください')\nButton1.bind(\"\",DeleteEntryValue1)\nButton1.pack()\nButton3 = Tkinter.Button(text = u'OK')\nButton3.bind(\"\",ChangeText1)\nButton3.pack()\n\nroot.mainloop()\n\n#Header削除と最大要素数の決定\ncolnum = 0\nfor i in range (count):\n\tdel anslist[i][0]\n\tif colnum < len(anslist[i]):\n\t\tcolnum = len(anslist[i])\n\n# 得点部分だけの配列を作成\nans=[[0 for j in range(colnum)] for k in range(len(anslist))]\n# 学籍番号部分だけの配列を作成\nstnum=[[0 for j in range(colnum)] for k in range(len(anslist))]\n\n# 学生番号と得点を分割するfor文\nfor i in range(count):\n\tfor row in range(0,len(anslist[i])):\n\t\tstnum [i][row] = anslist[i][row][0]\n\t\tans [i][row] = anslist[i][row][21]\n\n# 学生番号と得点が共に空欄のものを削除\nfor i in range(count):\n\tfor row in range(0,len(ans[i])-1):\n\t\tif stnum[i][row]=='' and ans [i][row]=='' :\n\t\t\tdel ans[i][row]\n\t\t\tdel stnum[i][row]\n\n# 学籍番号を全講義から抽出してリスト化\nstnum_count = [0 for i in range(colnum*len(anslist))]\nplus = 0\nfor i in range(count):\n\tfor j in range(0,len(stnum[i])):\n\t\tstnum_count[plus] = stnum[i][j]\n\t\tplus = plus + 1\nstnum_list = []\nfor i in stnum_count:\n\tif i not in stnum_list:\n\t\tstnum_list.append(i)\nfor i in range(len(stnum_list)):\n\tif stnum_list[i] == 0 :\n\t\tdel stnum_list[i]\n\n# 合計結果をまとめる配列\nresult = [['' for j in range(16)] for k in range(len(stnum_list))]\n\n#学籍番号ごとに各回の得点を配列に格納\nfor i in range(len(result)):\n\tif result[i][0] == '' and stnum_list[i] != '0':\n\t\tresult[i][0] = stnum_list[i]\n\tfor j in range(count):\n\t\tfor k in range(len(stnum[j])):\n\t\t\tif result[i][0] == stnum[j][k]:\n\t\t\t\tresult[i][j+1] = ans[j][k]\n\t\t\t\tbreak\n\nfor i in range(len(result)-2):\n\tif result[i][0] == '' or result[i][0] == '0':\n\t\tdel result[i]\n\n# 全講義の合計得点を配列の最終列に格納\nfor i in range(len(result)):\n\tscore_sum = 0\n\tfor j in range(1,len(result[0])-1):\n\t\tif result[i][j] != '':\n\t\t\tscore_sum = score_sum + int(result[i][j])\n\tresult[i][15] = score_sum\n\n# 学籍番号順でソート\nscoresheet = sorted(result, key=lambda x:(x[0],-int(x[15])))\n\n# 1行目に項目を追加\nheader = [\"StudentNumber\",'No.1','No.2','No.3','No.4','No.5','No.6','No.7','No.8','No.9','No.10','No.11','No.12','No.13','No.14',\"TotalScore\"]\noutput = np.vstack((header, scoresheet))\n\n# ワークブックとワークシートを作成\nwb = xlsxwriter.Workbook(outfname+\"-SmallTests.xlsx\")\nws = wb.add_worksheet(\"TotalScoreSheet\")\n\n# データ入力\nfor i in range(0,len(output)):\n for j in range(0,len(output[0])):\n ws.write(i, j, output[i][j])\n\n# 書き込み\nwb.close()\n\nprint(\"完了\")\n","sub_path":"ISE_SmallTest_Total.py","file_name":"ISE_SmallTest_Total.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"641941389","text":"import socket\nimport time\nimport json\nimport datetime\nimport MySQLdb\nfrom random import randint\nfrom decimal import *\nimport subprocess\nimport docker\nfrom rpc_utils import *\nimport os \n\n\n\nif __name__ == '__main__':\n # name of the data base\n\tminer_server=\"localhost\"\n\tdb_list=[]\n\tclient = docker.from_env() \n\tdb = MySQLdb.connect(host=\"localhost\", # your host, usually localhost\n\tuser=\"vicom\", # your username\n\tpasswd=\"vicom\", # your password\n\tdb=\"db\") \n\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ts.connect((\"8.8.8.8\", 80))\n\tip=s.getsockname()[0]\n\ts.close()\n\tend=False\n\tlenght=0\n\tadd=[]\n\tmaxi=120000\n\tcur = db.cursor()\n\twhile(lenght<=maxi):\n\t\ttry:\n\t\t\tnn=rpc_call(client, ip, \"getnewaddress\",\"''\")\n\t\texcept:\n\t\t\tnn=0\n\t\tif(nn!=\"\" and nn!=False and nn!=None and nn!=0):\n\t\t\tadd=[nn,ip]\n\t\t\tquery = ('INSERT INTO destination (address,IP) values (%s,%s)')\n\t\t\tend = True\n\t\t\tcur.execute(query, add)\n\t\t\tdb.commit()\n\t\t\tf = open(\"address.csv\", \"a\")\n\t\t\tf.write(str(nn)+\",\"+str(ip)+\"\\n\")\n\t\t\tf.close()\n\t\t\tlenght=lenght+1\n\t\t#if(lenght>=maxi):\n\t\t#\trpc_call(client,ip,\"dumpwallet\",\"'walletdump'\")\n","sub_path":"btc_testbed/lib/generate_destination.py","file_name":"generate_destination.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"209432408","text":"from __future__ import absolute_import\nimport numpy as np\nfrom lsst.sims.catalogs.generation.db import DBObject\n\n__all__ = ['dbInterface']\n\nclass dbInterface(object):\n\n def __init__(self, database, host, port, driver):\n\n self._dbo = DBObject(database=database, host=host, port=port,\n driver=driver)\n\n def forcedSourceFromId(self, objectId):\n\n dtype = np.dtype([('object_id', np.int),\n ('ccd_visit_id', np.int),\n ('psf_flux', np.float),\n ('psf_flux_err', np.float),\n ('flags', np.int)])\n query = \"\"\"select objectId, ccdVisitId, psFlux, psFlux_Sigma, flags\n from ForcedSource\n where objectId = %i\"\"\" % objectId\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n\n def visitFromCcdVisitId(self, visitId):\n\n dtype = np.dtype([('visit_id', np.int),\n ('filter', str, 300),\n ('obs_start', str, 300)])\n\n query = \"\"\"select visitId, filterName, obsStart\n from CcdVisit\n where ccdVisitId = %i\"\"\" % visitId\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n\n def objectFromId(self, objectId):\n\n dtype = np.dtype([('object_id', np.int),\n ('parent_object_id', np.int),\n ('ra', np.float),\n ('dec', np.float)])\n query = \"\"\"select objectId, parentObjectId, psRa, psDecl\n from Object\n where objectId = %i\"\"\" % objectId\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n\n def objectFromRaDec(self, ra, dec, tol):\n\n dtype = np.dtype([('object_id', np.int),\n ('parent_object_id', np.int),\n ('ra', np.float),\n ('dec', np.float)])\n query = \"\"\"select objectId, parentObjectId, psRa, psDecl\n from Object\n where (psRa > %f) and (psRa < %f)\n and (psDecl > %f) and (psDecl < %f)\"\"\" % (ra - tol,\n ra + tol,\n dec - tol,\n dec + tol)\n results = self._dbo.execute_arbitrary(query, dtype=dtype)\n return results\n","sub_path":"python/desc/monitor/dbConnection.py","file_name":"dbConnection.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"492498331","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 4 14:18:03 2019\r\n\r\n@author: vibinan\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\r\nfrom keras.preprocessing.text import Tokenizer\r\nfrom keras.preprocessing import sequence\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, LSTM, Embedding\r\nfrom keras.backend import clear_session\r\n\r\n\r\n\r\n\r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\nimport pandas as pd \r\n\r\nfrom keras.models import Sequential \r\nfrom keras.layers import Dense \r\nfrom keras.layers import LSTM \r\nfrom keras.layers import Dropout \r\n\r\n## Import Dataset\r\n\r\n# Dataset link - https://finance.yahoo.com/quote/AAPL/history?p=AAPL&.tsrc=fin-srch\r\n\r\napple_training_complete = pd.read_csv(r'E:\\Datasets\\apple_training.csv') \r\n\r\napple_training_processed = apple_training_complete.iloc[:, 1:2].values \r\n\r\n\r\n## Data Normalization\r\n\r\nfrom sklearn.preprocessing import MinMaxScaler \r\nscaler = MinMaxScaler(feature_range = (0, 1))\r\n\r\napple_training_scaled = scaler.fit_transform(apple_training_processed)\r\n\r\n## Convert Training Data to Right Shape\r\n\r\nfeatures_set = [] \r\nlabels = [] \r\nfor i in range(60, 1260): \r\n features_set.append(apple_training_scaled[i-60:i, 0])\r\n labels.append(apple_training_scaled[i, 0])\r\n \r\nfeatures_set, labels = np.array(features_set), np.array(labels) \r\n\r\nfeatures_set = np.reshape(features_set, (features_set.shape[0], features_set.shape[1], 1)) \r\n\r\n### Training The LSTM\r\n\r\nmodel = Sequential() \r\n\r\nmodel.add(LSTM(units=50, return_sequences=True, input_shape=(features_set.shape[1], 1))) \r\n\r\nmodel.add(Dropout(0.2)) \r\n\r\nmodel.add(LSTM(units=50, return_sequences=True)) \r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(LSTM(units=50, return_sequences=True)) \r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(LSTM(units=50)) \r\nmodel.add(Dropout(0.2)) \r\n\r\n### Creating Dense Layer\r\n\r\nmodel.add(Dense(units = 1))\r\n\r\n### Model Compilation\r\n\r\nmodel.compile(optimizer = 'adam', loss = 'mean_squared_error') \r\n\r\n### Algorithm Training\r\n\r\nmodel.fit(features_set, labels, epochs = 100, batch_size = 32) \r\n\r\n### Testing our LSTM\r\n\r\napple_testing_complete = pd.read_csv(r'E:\\Datasets\\apple_testing.csv') \r\napple_testing_processed = apple_testing_complete.iloc[:, 1:2].values\r\n\r\n### Converting Test Data to Right Format\r\n\r\napple_total = pd.concat((apple_training_complete['Open'], apple_testing_complete['Open']), axis=0) \r\n\r\ntest_inputs = apple_total[len(apple_total) - len(apple_testing_complete) - 60:].values \r\n\r\n\r\ntest_inputs = test_inputs.reshape(-1,1) \r\ntest_inputs = scaler.transform(test_inputs) \r\n\r\n\r\ntest_features = [] \r\nfor i in range(60, 80): \r\n test_features.append(test_inputs[i-60:i, 0])\r\n \r\ntest_features = np.array(test_features) \r\ntest_features = np.reshape(test_features, (test_features.shape[0], test_features.shape[1], 1)) \r\n\r\n## Making Predictions\r\n\r\npredictions = model.predict(test_features) \r\n\r\npredictions = scaler.inverse_transform(predictions) \r\n\r\n\r\nplt.figure(figsize=(10,6)) \r\nplt.plot(apple_testing_processed, color='blue', label='Actual Apple Stock Price') \r\nplt.plot(predictions , color='red', label='Predicted Apple Stock Price') \r\nplt.title('Apple Stock Price Prediction') \r\nplt.xlabel('Date') \r\nplt.ylabel('Apple Stock Price') \r\nplt.legend() \r\nplt.show() \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"timeseries - lstm.py","file_name":"timeseries - lstm.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"354490560","text":"import pandas as pd\nimport numpy as np\nimport datetime\n\n# create some mock data\n\ndata_eye = [(pd.Timestamp(1513393355, unit= 's'), pd.Timestamp(1513393463, unit= 's'), 90),\n (pd.Timestamp(1513393853, unit= 's'), pd.Timestamp(1513393900, unit= 's'), 80),\n (pd.Timestamp(1513394100, unit= 's'), pd.Timestamp(1513394500, unit ='s'), 150),\n (pd.Timestamp(1513394900, unit= 's'), pd.Timestamp(1513395300, unit= 's'), 85)]\ndf_eye = pd.DataFrame(data=data_eye, columns=['start', 'end', 'pixel'])\n\ndata_event = [(pd.Timestamp(1513393300, unit= 's'), pd.Timestamp(1513393450, unit= 's'), 'a'),\n (pd.Timestamp(1513393851, unit= 's'), pd.Timestamp(1513393876, unit= 's'), 'b'),\n (pd.Timestamp(1513393877, unit= 's'), pd.Timestamp(1513394177, unit= 's'), 'c'),\n (pd.Timestamp(1513394178, unit= 's'), pd.Timestamp(1513394580, unit= 's'), 'a')]\ndf_event = pd.DataFrame(data=data_event, columns=['start', 'end', 'event'])\n\n# print (df_eye)\n# print (df_event)\n\ntime_periods = pd.DataFrame({'time': pd.date_range(start = df_eye.start.min(), end = df_eye.end.max(), freq = 'S')}) #create all time-stamps\ndf_eye = time_periods.merge(df_eye, how='left', left_on='time', right_on='start').fillna(method='pad') #merge\n# print (new_eye.iloc[70:150])\nmask_eye = (df_eye['time'] > df_eye['start']) & (df_eye['time'] < df_eye['end'])\ndf_eye = df_eye.where(mask_eye)\ndf_eye = df_eye.dropna()\n# print (fixed_eye.iloc[70:150])\ndf_eye.pop('start')\ndf_eye.pop('end')\n# df_eye.index = df_eye['time']\n# df_eye.pop('time')\ndf_eye['ID'] = 'ID_num'\ndf_eye['design'] = 'design_num'\n\n# df_eye.set_index([df_eye['ID']],[df_eye['design']])\n# df_eye.index = ([df_eye['ID']],[df_eye['design']])\n# df_eye.index = df_eye['design']\n# indexes = [df_eye['ID']],[df_eye['design']]\n\n# df_eye.set_index(['ID', 'design'], inplace = True, \n# append = False, drop = False) \n\nindex = pd.MultiIndex.from_product([['id_num'], ['design_num']],\n names=['ID', 'design']) \n# index = pd.MultiIndex.from_tuples(indexes,names = ['ID','design'])\ncolumns = pd.MultiIndex.from_product([['time', 'condition', 'aveH', 'aveV']],\n names = [None]) \ndf_eye_new = pd.DataFrame(df_eye, index=index, columns=columns)\n\n# df_eye2 = df_eye.reindex (index)\ndf_eye_new.append(df_eye).reset_index().set_index(keys=['ID', 'design'])\n\n\nprint (df_eye)\n# print (df_eye_new)\n\n\ntime_periods_event = pd.DataFrame({'time': pd.date_range(start = df_event.start.min(), end = df_event.end.max(), freq = 'S')}) #create all time-stamps\ndf_event = time_periods_event.merge(df_event, how='left', left_on='time', right_on='start').fillna(method='pad') #merge\nmask_event = (df_event['time'] > df_event['start']) & (df_event['time'] < df_event['end'])\ndf_event = df_event.where(mask_event)\ndf_event = df_event.dropna()\ndf_event.pop('start')\ndf_event.pop('end')\ndf_event.index = df_event['time']\ndf_event.pop('time')\n# print (df_event)\n\ndf_all = pd.concat ([df_event, df_eye], axis=1, sort = True)\ndf_all = df_all.dropna()\n\n# print (df_all.iloc[70:200])\n","sub_path":"old_drafts/Goni/old/concat_df_without_method3.py","file_name":"concat_df_without_method3.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"292337586","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nPython Codes for Chapter: \nInsights from MAPs\n\n@author: JoseManuel\n\"\"\"\n#%%\nimport pandas as pd\n\nlink1='https://github.com/resourcesbookvisual/data/'\nlink2='raw/master/contriWA.csv'\ncontriWA=pd.read_csv(link1+link2)\n \n \n\n#%%\nimport geopandas as gpd\n\nmyGit=\"https://github.com/resourcesbookvisual/data/\"\nmyGeo=\"raw/master/WAzipsGeo.json\"\nmapLink=myGit + myGeo\n\nwazipMap = gpd.read_file(mapLink)\n\n#%%\n\nwazipMap.plot()\n\n#%%\nimport geoplot as gplt\ngplt.polyplot(wazipMap)\n\n\n#%%\n\nwazipMap.ZCTA5CE10.describe()\n\n#%%\n\n# Filtering\n#conditions\ncondition1='election_year==2012 and cash_or_in_kind==\"Cash\"'\ncondition2='party.isin([\"DEMOCRAT\",\"REPUBLICAN\"])'\n\n#chained queries\ncontriWASub=contriWA.query(condition1).query(condition2)\n#%%\n# Aggregating\ncontrisum=contriWASub.groupby(['contributor_zip','party'])\ncontrisum=contrisum.agg({'amount':'sum'}).reset_index().fillna(0)\ncontrisum=contrisum.pivot(index='contributor_zip', \n columns='party', \n values='amount').reset_index().fillna(0)\ncontrisum['total']=contrisum.DEMOCRAT + contrisum.REPUBLICAN\n\n\ncontrisum\n#\n\n\n#%%%\n\nwazipMap=wazipMap.loc[:,['ZCTA5CE10','geometry']]\n# contributor_zip as text (it was a number)\ncontrisum.contributor_zip=contrisum.contributor_zip.astype(str)\nallZip=wazipMap.merge(contrisum,\n left_on='ZCTA5CE10',\n right_on='contributor_zip',\n how='left')\n\n#%%\nimport numpy as np\n\ncomparison=allZip.REPUBLICAN>allZip.DEMOCRAT\ncondition=allZip.loc[:,[\"REPUBLICAN\",\"DEMOCRAT\"]].any(axis=1)\nallZip['winnerREP']=condition1\nallZip['winnerREP']=np.where(condition,\n comparison,\n None)\n\n\n#%%\n\nallZip.plot(column='winnerREP', #column to color\n categorical=True,\n edgecolor='black',\n legend=True,\n missing_kwds={'color': 'lightgrey'},\n cmap='gist_gray') # palette for column chosen\n\n\n\n#%%\n\n#missing\nallZip[allZip.winnerREP.isnull()].shape[0]\n\n\n#%%\n\n\n# dissolve\n## a. make copy\nwaBorder=wazipMap.copy()\n## b. Correct map with buffer (may not be needed)\nwaBorder['geometry'] = waBorder.buffer(0.01)\n## c. create a constant column by which to dissolve\nwaBorder['dummy']=1\n## d. dissolving\nwaBorder= waBorder.dissolve(by='dummy')\n## e. plot the dissolved map\nwaBorder.plot(color='white',edgecolor='black')\n\n\n#%%\n\n\n# dissolve\n## a. make copy\nallZipBetter=allZip.copy()\n## a.1 saving missing values\nNAs = allZipBetter[allZipBetter.winnerREP.isna()]\n## b. Correct map with buffer (may not be needed)\nallZipBetter['geometry'] = allZipBetter.buffer(0.01)\n## c. dissolving\nallZipREP= allZipBetter.dissolve(by='winnerREP',as_index=False)\n## d. plotting the dissolved map\nallZipREP.append(NAs).plot(column='winnerREP', #column to color\n edgecolor='black',\n categorical=True,legend=True,\n missing_kwds={'color': 'grey'}, \n cmap='gist_gray') \n\n#%%\n\n\n# turn lon lat into geoDataFrame \nWApoints = gpd.GeoDataFrame(contriWASub, \n geometry=gpd.points_from_xy(contriWASub.Lon,\n contriWASub.Lat))\nWApoints.crs = wazipMap.crs\n\nWApoints.plot()\n\n#%%\n\n## a. make polygons with missing values\nallZipNA=allZip[allZip.total.isnull()].copy()\n## b. Correct map with buffer (may not be needed)\n#allZipNA['geometry'] = allZipNA.buffer(0.01)\n## c. create a constant column by which to dissolve\n#allZipNA['dummy']=1\n## d. dissolving\n#allZipNA= allZipNA.dissolve(by='dummy',as_index=False)\n\n\n#%%\n\n#plot with default projection in geopandas\nlayerBorder= waBorder.plot(edgecolor='grey',color='white')\n\nlayerMissing=allZipNA.plot(edgecolor='grey',color='grey',\n ax=layerBorder)\nWApoints.plot(color='black', \n markersize=0.1,alpha=0.1,\n ax=layerBorder) # on top of!)\n\n\n\n\n\n\n#%%\n\n#plot with default projection in geoplot\nlayerBorder = gplt.polyplot(waBorder,\n edgecolor='grey',\n facecolor='white')\nlayerMissing = gplt.polyplot(allZipNA,\n edgecolor='grey',\n facecolor='grey',\n ax=layerBorder)\ngplt.pointplot(WApoints,\n color='black',\n s=0.1,#size of point\n alpha=0.1,\n ax=layerBorder)# on top of!\n\n\n#%%\n\n#reprojecting with geopandas\nlayerBorder= waBorder.to_crs(\"EPSG:3395\").plot(edgecolor='grey', \n color='white')\n\nlayerMissing=allZipNA.to_crs(\"EPSG:3395\").plot(edgecolor='grey',\n color='grey',\n ax=layerBorder)\n\nWApoints.to_crs(\"EPSG:3395\").plot(color='black',\n markersize=0.1,\n alpha=0.1,\n ax=layerBorder)\n\n\n#%%\n\nimport geoplot.crs as gcrs #activating!\n\nlayerBorder = gplt.polyplot(waBorder, \n projection=gcrs.Mercator(),#HERE!\n edgecolor='grey', \n facecolor='white')\n\nlayerMissing = gplt.polyplot(allZipNA,\n edgecolor='grey',\n facecolor='grey',\n ax=layerBorder)\nlayerPoint= gplt.pointplot(WApoints,\n color='black',\n s=0.1,\n alpha=0.1,\n ax=layerBorder)# on top of!\n\n\n#%%\n\nmyGit=\"https://github.com/resourcesbookvisual/data/\"\nmyGeo2=\"raw/master/waCountiesfromR.geojson\"\nmapLink2=myGit + myGeo2\n\nwaCounties= gpd.read_file(mapLink2)\n\nkingMap=waCounties[waCounties.JURISDIC_2==\"King\"]\n\n#%%\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()#plt.subplots(figsize=(10,6))\n# zooming area:\nax.set_xlim(kingMap.total_bounds[0:4:2]) #recovering indices\nax.set_ylim(kingMap.total_bounds[1:5:2]) #recovering indices\n# maps of WASHINGTON\nBorder= waBorder.plot(edgecolor='grey',color='white',ax=ax)\nZips=wazipMap.plot(edgecolor='silver',color='whitesmoke',ax=Border)\n# ZOOMING IN:\nWApoints.plot(color='black',markersize=0.1,alpha=0.1,ax=Border)\nplt.show()\n\n\n\n\n#%%\n# keeping non-missing data\nallZip=allZip[~allZip.total.isnull()]\n\n#plotting absolute values\n#forDems\nBorder= waBorder.plot(edgecolor='grey',color='red')\nallZip.plot(column='DEMOCRAT',ax=Border)\n\n#forAll\nBorder= waBorder.plot(edgecolor='grey',color='red')\nallZip.plot(column='total',ax=Border)\n\n#plotting relative values\nBorder= waBorder.plot(edgecolor='grey',color='red')\nallZip['DemChoro'] = allZip.DEMOCRAT / allZip.total\nallZip.plot(column='DemChoro',legend=True,ax=Border,\n legend_kwds={'shrink': 0.6}) #shrink legend size\n\n#%%\n\n## geoplot\n#plotting absolute values\n#forDems\nBorder = gplt.polyplot(waBorder,\n edgecolor='grey', \n facecolor='red')\ngplt.choropleth(allZip, hue='DEMOCRAT',ax=Border)\n\n#forAll\nBorder = gplt.polyplot(waBorder,\n edgecolor='grey', \n facecolor='red')\ngplt.choropleth(allZip, hue='total',ax=Border)\n\n#plotting relative values\nBorder = gplt.polyplot(waBorder,\n edgecolor='grey', \n facecolor='red')\ngplt.choropleth(allZip, hue='DemChoro',ax=Border, legend=True)\n\n\n\n#%%\n\n\nlink3='raw/master/covidCountyWA.csv'\nLINK=link1 + link3\n#getting the data TABLE from the file in the cloud:\ncovid=pd.read_csv(LINK)\n\n#%%\n\ncovidMap=pd.merge(waCounties.loc[:,[\"JURISDIC_2\",\"geometry\"]],covid,\n left_on=\"JURISDIC_2\",right_on=\"County\")\n\n\n#%%\n\nimport mapclassify as mc\n\n#well-known styles\n#geopandas for Equal intervals\ncovidMap.plot(column='CasesPer100k',\n scheme='EqualInterval', \n k=5,\n cmap='OrRd',\n legend=True)\n#%%\n#geopandas for Quantiles\ncovidMap.plot(column='CasesPer100k',\n scheme='Quantiles', \n k=5,\n cmap='OrRd',\n legend=True)\n\n#%%\n\n#well-known styles\n#geoplot for Equal intervals\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.EqualInterval(covidMap.CasesPer100k,k=5),\n cmap='OrRd',\n legend=True)\n#%%\n#geoplot for Quantiles\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.Quantiles(covidMap.CasesPer100k, k=5),\n cmap='OrRd',\n legend=True)\n\n#%%\n#optimization styles in geopandas\ncovidMap.plot(column='CasesPer100k',\n scheme='FisherJenks', \n k=5,\n cmap='OrRd',\n legend=True)\n#%%\ncovidMap.plot(column='CasesPer100k',\n scheme='HeadTailBreaks',\n cmap='OrRd',\n legend=True)\n#%%\n#optimization styles in geoplot\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.FisherJenks(covidMap.CasesPer100k, k=5),\n cmap='OrRd',\n legend=True)\n#%%\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.HeadTailBreaks(covidMap.CasesPer100k),\n cmap='OrRd',\n legend=True)\n\n#%%\n#new variable\nvaluesNew=100000*(covidMap.Deaths/covidMap.Population)\ncovidMap['DeathsPer100k']=valuesNew\n\n#%%\nimport geoplot.crs as gcrs #activating!\n\n#border\nborder=gplt.polyplot(df=covidMap,\n projection=gcrs.Mercator(),#reproject\n edgecolor='gray', #border\n facecolor='gainsboro') #fill of polygon\n#area and color\ngplt.cartogram(df=covidMap,#map\n scheme=mc.EqualInterval(covidMap.DeathsPer100k,k=3),\n cmap=plt.get_cmap('YlGnBu',3),#palette\n hue=\"DeathsPer100k\", #var for color \n scale='CasesPer100k',#var for resize\n limits=(0.3, 1), #limits cartogram polygons \n edgecolor='None', #no border\n legend=True,\n legend_var='hue', #legend of what\n legend_kwargs={'bbox_to_anchor': (0.1, 0.4),#location\n 'frameon': True, #with frame?\n 'markeredgecolor':'k',\n 'title':\"DeathsPer100k\"},\n ax=border)\n#%%\n# mapOfPoints\n\nimport geoplot.crs as gcrs #activating!\n\n#borders\ncountyBorders = gplt.polyplot(df=covidMap, \n projection=gcrs.Mercator(),#HERE!\n edgecolor='grey',\n facecolor='gainsboro')\n\n#points scaled\ncovidMap['centroid']=covidMap.centroid #compute centroids\ngplt.pointplot(df=covidMap.set_geometry('centroid'), #set geometry\n scheme=mc.EqualInterval(covidMap.DeathsPer100k,k=3),\n cmap='YlGnBu',#palette\n hue=\"DeathsPer100k\", \n scale='CasesPer100k', #sizes of points \n limits=(4, 40), #range for sizes of points \n legend=True,\n legend_var='hue',\n legend_kwargs={'bbox_to_anchor': (1, 1),\n 'frameon': True,\n 'markeredgecolor':'k',\n 'title':\"DeathsPer100k\"},\n extent = covidMap.total_bounds,\n ax=countyBorders)\nplt.show()\n\n\n#%%\n\ncounties=gplt.polyplot(waCounties,edgecolor= 'silver')\n\ngplt.kdeplot(WApoints,\n shade=False,\n shade_lowest=False,\n ax=counties)\n\n\n#%% for republicans\n\ncounties=gplt.polyplot(waCounties,edgecolor= 'black',\n projection=gcrs.Mercator())#reproject)\n\ngplt.kdeplot(WApoints[WApoints.party=='REPUBLICAN'], #subset\n shade=True, \n cmap='Reds',\n shade_lowest=False,\n ax=counties,\n extent=kingMap.total_bounds)\n\n\n#%% for democrats\n\ncounties=gplt.polyplot(waCounties,edgecolor= 'black',\n projection=gcrs.Mercator())#reproject)\ngplt.kdeplot(WApoints[WApoints.party=='DEMOCRAT'], #subset\n shade=True, \n cmap='Blues',\n shade_lowest=False,\n ax=counties,\n extent=kingMap.total_bounds)\n\n\n#%% \n\nimport matplotlib.pyplot as plt\n#import matplotlib.cbook as cbook\nfrom matplotlib_scalebar.scalebar import ScaleBar\n\nplt.figure()\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.HeadTailBreaks(covidMap.CasesPer100k),\n cmap='OrRd',\n legend=True)\n#image = plt.imread(cbook.get_sample_data('grace_hopper.png'))\n#plt.imshow(image)\nscalebar = ScaleBar(1,'m') # 1 pixel = 0.2 meter\nplt.gca().add_artist(scalebar)\nplt.show()\n\n#%%\n\nfig, ax = plt.subplots(figsize=(10, 10))\ngplt.choropleth(covidMap, \n hue='CasesPer100k', \n scheme=mc.HeadTailBreaks(covidMap.CasesPer100k),\n cmap='OrRd',\n legend=True,\n legend_kwargs={'bbox_to_anchor': (1, 1),\n 'frameon': True,\n 'markeredgecolor':'k',\n 'title':\"DeathsPer100k\"},\n extent = covidMap.total_bounds,\n ax=ax)\n\nx, y, arrow_length = 0, 0.3, 0.3\nax.annotate('N', xy=(x, y), \n xytext=(x, y-arrow_length),\n arrowprops=dict(facecolor='black',\n width=5,\n headwidth=15),\n ha='center', va='center', fontsize=20,\n xycoords=ax.transAxes)\nplt.show()\n\n","sub_path":"python/geospatial.py","file_name":"geospatial.py","file_ext":"py","file_size_in_byte":13715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"181325218","text":"# -*- coding: ISO-8859-1 -*-\nimport localconfig\nimport ConfigParser \nimport tasbot\nfrom tasbot.customlog import Log\n \nclass LoadCFG:\n\tdef __init__ (self, Class):\n\t\tself.Server = Class\n\t\tself.Debug = Class.Debug\n\t\tself.LoadCFG ()\n\t\n\tdef LoadCFG (self):\n\t\tself.Debug (\"Load CFG\")\n\t\ttry:\n\t\t\tself.Server.Config = localconfig.Server\n\t\texcept:\n\t\t\tLog.Error('using default server config')\n\t\t\tself.Server.Config = {\n\t\t\t\t'LobbyServer':{'Host':'springrts.com', 'Port':8200},\n\t\t\t\t'MainAccount':'[pyah]Master',\n\t\t\t\t'UnitsyncPath':'/usr/lib/libunitsync.so',\n\t\t\t\t'SpringExec':'/usr/bin/spring-dedicated'\n\t\t\t}\n\t\ttry:\n\t\t\tself.Server.Groups = localconfig.Groups\n\t\texcept:\n\t\t\tLog.Error('using default server config')\n\t\t\tself.Server.Groups = {\n\t\t\t\t'pyah':{\n\t\t\t\t\t'Mod':'Evolution RTS - v1.5',\n\t\t\t\t\t'Map':'Comet Catcher Redux',\n\t\t\t\t\t'ChannelsReport':[['autohostdev']],\n\t\t\t\t\t'Accounts':[('[pyah]Host_01','PASSWORD',0)]\n\t\t\t\t},\n\t\t\t}\n\t\tself.IP = localconfig.IP\n\t\t\n\t\tself.Server.AccessCommands = {\n\t\t\t'code':['owner', 'admin'],\n\t\t\t'udp':['owner'],\n\t\t\t'start':['owner', 'admin', '%BattlePlayer%'],\n\t\t\t'kick':['owner', 'admin', 'operator'],\n\t\t\t'ring':['admin', 'operator', '%BattlePlayer%', '%GamePlayer%'],\n\t\t}\n\t\tself.Server.AccessRoles = {\n\t\t\t'owner':{\n\t\t\t\t'[CN]Zydox':1,\n\t\t\t\t'_koshi_':1,\n\t\t\t\t'BrainDamage':1,\n\t\t\t},\n\t\t\t'admin':{\n\t\t\t\t'[CN]Zydox':1,\n\t\t\t\t'_koshi_':1,\n\t\t\t\t'BrainDamage':1,\n\t\t\t},\n\t\t\t'operator':{\n\t\t\t},\n\t\t}\n","sub_path":"loadCFG.py","file_name":"loadCFG.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"274598891","text":"import io\nimport os\nimport time\nimport re\nimport string\nfrom json import dumps\nfrom PIL import Image, ImageFilter\n\nimport requests\n# import spacy\n# from tesserocr import PyTessBaseAPI\nimport numpy as np\nimport pandas as pd\nfrom keras.preprocessing import image\nfrom keras.applications.inception_v3 \\\n import InceptionV3, decode_predictions, preprocess_input\n\nfrom nk_croc.is_a import isa_dict\nfrom nk_croc.id_mapping import id_mapping_dict\n\nrequests_session = requests.Session() if os.environ.get('USE_REQUESTS_SESSION') == \"True\" else requests\n# GET_IMAGE_TIMEOUT is max number of seconds to wait before triggering timeout error when downloading an image\nget_image_timeout = int(os.environ.get(\"GET_IMAGE_TIMEOUT\", \"10\"))\n\nclass Croc():\n\n def __init__(self):\n self.target_size = (299, 299)\n self.model = InceptionV3(weights='imagenet')\n # self.nlp = spacy.load('en_core_web_md')\n self.n_top_preds = 10\n # self.isa_dict = isa_dict\n # self.id_mapping_dict = id_mapping_dict\n\n def load_image(self, img_path, prep_func=lambda x: x):\n ''' load image given path and convert to an array\n '''\n img = image.load_img(img_path, target_size=self.target_size)\n x = image.img_to_array(img)\n return prep_func(x)\n\n def load_image_from_web(self, image_url):\n ''' load an image from a provided hyperlink\n '''\n # get image with timout\n # More info on using request with timeouts: http://docs.python-requests.org/en/master/user/quickstart/#timeouts\n response = requests_session.get(image_url, timeout=get_image_timeout)\n with Image.open(io.BytesIO(response.content)) as img:\n # fill transparency if needed\n if img.mode in ('RGBA', 'LA'):\n img = self.strip_alpha_channel(img)\n\n # convert to jpeg\n if img.format is not 'jpeg':\n img = img.convert('RGB')\n img.save('target_img.jpg')\n\n def validate_url(self, url):\n url_validator = re.compile(\n r'^(?:http|ftp)s?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' #domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n\n return bool(url_validator.match(url))\n\n def cleanup_text(self, raw_chars):\n ''' use spacy to clean text and find tokens\n '''\n doc = self.nlp(raw_chars, disable=['parser', 'ner'])\n\n # grab raw text while removing any hanging newlines\n text = [t.text for t in doc if t.text.replace(' ', '').replace('\\n', '')]\n\n tokens = [tok.lemma_.strip() for tok in doc\n if self.nlp.vocab.has_vector(str(tok)) and # is_oov currently (v2.0.11) broken\n tok.lemma_ != '-PRON-']\n\n tokens = [tok for tok in tokens\n if tok not in self.nlp.Defaults.stop_words and\n tok not in string.punctuation]\n\n return dict(tokens=list(set(tokens)), text=text)\n\n def classify_objects(self, image_array, decode_func):\n ''' Returns binary array with ones where the model predicts that\n the image contains an instance of one of the target classes\n (specified by wordnet id)\n '''\n predictions = self.model.predict(image_array)\n # decode the results into list of tuples (class, description, probability)\n predictions = decode_func(predictions, top=self.n_top_preds)\n return predictions\n\n def strip_alpha_channel(self, image, fill_color='#ffffff'):\n ''' Strip the alpha channel of an image and fill with fill color\n '''\n background = Image.new(image.mode[:-1], image.size, fill_color)\n background.paste(image, image.split()[-1])\n return background\n\n def char_detect(self, img_path):\n ''' Run tesseract ocr on an image supplied\n as an image path.\n '''\n with PyTessBaseAPI() as ocr_api:\n with Image.open(img_path) as image:\n # fill image alpha channel if it exists\n if image.mode in ('RGBA', 'LA'):\n image = self.strip_alpha_channel(image)\n\n # will need a better preprocessing approach here\n # if we stay with tesseract:\n image = image.convert('L')\n # image = image.filter(ImageFilter.SHARPEN)\n # image = image.filter(ImageFilter.EDGE_ENHANCE)\n\n\n ocr_api.SetImage(image)\n raw_chars = ocr_api.GetUTF8Text()\n # char_confs = ocr_api.AllWordConfidences()\n\n text = self.cleanup_text(raw_chars)\n\n return text\n\n def climb_hierarchy(self, objects):\n\n def climb(self, object_, tree_):\n ''' function to climb the wordnet tree hierarchy and\n return the concepts along the branch.\n '''\n try:\n target_id = self.isa_dict[object_]\n target_label = self.id_mapping_dict[object_]\n tree_.append(dict(id=target_id, labels=target_label))\n climb(self, target_id, tree_)\n\n except Exception as e:\n e\n\n return tree_\n\n # trace branch to root for each object\n object_trees = list()\n for object_ in objects:\n tree_ = list()\n\n complete_tree = climb(self, object_, tree_)\n object_trees.extend(complete_tree)\n\n return object_trees\n\n def predict(self, input_path):\n ''' Produce predictions for objects and text\n '''\n image_path = input_path\n\n if self.validate_url(image_path):\n filename = 'target_img.jpg'\n self.load_image_from_web(image_path)\n else:\n filename = image_path\n\n print('preprocessing image')\n X = np.array(\n [self.load_image(\n filename, prep_func=preprocess_input)])\n\n print('making object predictions')\n object_predictions = self.classify_objects(X, decode_predictions)\n\n object_predictions = pd.DataFrame.from_records(\n object_predictions[0], columns=['id', 'label', 'confidence'])\n\n # object_trees = self.climb_hierarchy(objects=object_predictions['id'])\n\n # print('performing character recognition')\n # char_predictions = self.char_detect(filename)\n\n if filename == 'target_img.jpg':\n os.remove('target_img.jpg')\n\n return dumps(dict(\n objects=object_predictions.to_dict(),\n object_trees='',\n text='',\n tokens=''))\n\n\nif __name__ == '__main__':\n client = Croc()\n image_path = 'http://i0.kym-cdn.com/photos/images/facebook/001/253/011/0b1.jpg'\n result = client.predict(input_path=image_path)\n print(result)\n","sub_path":"nk_croc/nk_croc.py","file_name":"nk_croc.py","file_ext":"py","file_size_in_byte":6996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"627214791","text":"import subprocess\nimport time\n\ncommand = \"ping www.google.com -t\"\nlast_timeout = []\ntimeout_markers = [\"timed out\", \"unreachable\"]\nprocess = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)\nfor line in iter(process.stdout.readline, \"\"):\n time.sleep(1)\n print(\"Current ping: {}\".format(line), end=\"\")\n if any([marker in line for marker in timeout_markers]):\n \tlast_timeout += [time.time()]\n if last_timeout: \n \ttimes = sorted([round(time.time() - timeout) for timeout in last_timeout])\n \tprint(\"Time outs [{}]: {} seconds\".format(len(times), times))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"513963689","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 19 18:39:26 2017\n\n@author: vsankar.la\n\"\"\"\nimport time\ntry:\n i=0\n while True:\n print(\"Hello\")\n i+=1\n if i>3:\n print(\"End of the loop\")\n break\n time.sleep(i)\n\n\nexcept Exception as e:\n print(e)","sub_path":"notes/PythonProblems/problem60.py","file_name":"problem60.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"126473586","text":"import pickle\nfrom utils import save_data_with_pickle, load_data_with_pickle\nfrom EntityEmbedder import EntityEmbedder\nfrom CorpusManager import CorpusManager\n\n\n# PATH in which utility files are stored\nPICKLES_PATH = '../../source_files/pickles/'\n\nFILE_ID = '18_3_max2words_100000'\nLENGTH = 100000\n\nOCCURRENCE_OF_ENTITIES_PATH = PICKLES_PATH + FILE_ID + 'word_occurrence_indexes'\nENTITY_DICT_PATH = PICKLES_PATH + FILE_ID + 'found_entity_dict'\n\nCORPUS_PATH = '/datahdd/vmanuel/ELMo/Corpora/shuffled_text_with_words'\n\nDATA_PATH = '../../source_files/vectors/'\nX_PATH = DATA_PATH + FILE_ID + 'X'\nY_PATH = DATA_PATH + FILE_ID + 'Y'\nentities_PATH = DATA_PATH + FILE_ID + 'entities'\n\nif __name__ == \"__main__\":\n entity_dict = load_data_with_pickle(ENTITY_DICT_PATH)\n\n c = CorpusManager()\n c.read_corpus(CORPUS_PATH, LENGTH)\n\n entity_embedder = EntityEmbedder()\n entity_embedder.setup(model_name = entity_embedder.ELMO_NAME,\n extraction_mode = entity_embedder.LAYER_2,\n occurrences_of_entities_path = OCCURRENCE_OF_ENTITIES_PATH,\n aggregation_method = entity_embedder.VECTOR_MEAN,\n corpus = c.corpus\n )\n\n entity_embedder.create_embedding_data_structure()\n entity_embedder.extract_vectors_of_occurrences_in_corpus()\n entity_embedder.create_dataset(entity_dict = entity_dict, \n X_PATH = X_PATH,\n Y_PATH = Y_PATH,\n entities_PATH = entities_PATH)\n\n\n ","sub_path":"preprocessing/generate_embedding_and_dataset_main_flow.py","file_name":"generate_embedding_and_dataset_main_flow.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"225045687","text":"import numpy as np\nfrom matplotlib import gridspec\nfrom IPython.display import display, HTML\nimport copy\nimport math\nimport time\n\n# import custom JS animator\nfrom mlrefined_libraries.JSAnimation_slider_only import IPython_display_slider_only\n \n# import standard plotting and animation\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import clear_output\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n######### centering and contrast-normalizing #########\ndef center(X):\n '''\n A function for normalizing each feaure dimension of an input array, mean-centering\n and division by its standard deviation\n \n '''\n X_means = np.mean(X,axis=0)[np.newaxis,:]\n X_normalized = X - X_means\n\n return X_normalized\n\ndef contrast_normalize(X):\n '''\n A contrast-normalizing function for image data pre-sphereing normalization.\n \n '''\n # compute and subtract off means\n X_means = np.mean(X,axis=0)[np.newaxis,:]\n X = X - X_means\n \n # divide off std of each image - remove any images deemed constant (whose std = 0)\n X_stds = np.std(X,axis=0)[np.newaxis,:]\n ind = np.argwhere(np.abs(X_stds) > 10**(-7))\n ind = np.array([s[1] for s in ind])\n X = X[:,ind]\n X_stds = X_stds[:,ind]\n X_normalized = X/X_stds\n \n # print report to user if any patches deemed constant\n report = np.shape(X_means)[1] - len(ind) \n if report > 0:\n print (str(report) + ' images of ' + str(np.shape(X_means)[1]) + ' imagses found to be constant, and so were removed')\n\n return X_normalized\n\n########## sphereing pre-processing functionality ##########\ndef compute_pcs(X,lam):\n '''\n A function for computing the principal components of an input data matrix. Both\n principal components and variance parameters (eigenvectors and eigenvalues of XX^T)\n are returned\n '''\n # create the correlation matrix\n P = float(X.shape[1])\n Cov = 1/P*np.dot(X,X.T) + lam*np.eye(X.shape[0])\n\n # use numpy function to compute eigenvalues / vectors of correlation matrix\n D,V = np.linalg.eigh(Cov)\n return V, D\n\ndef pca_transform_data(X,**kwargs):\n '''\n A function for producing the full PCA transformation on an input dataset X. \n '''\n # user-determined number of principal components to keep, and regularizer penalty param\n num_components = X.shape[0]\n if 'num_components' in kwargs:\n num_components = kwargs['num_components']\n lam = 10**(-7)\n if 'lam' in kwargs:\n lam = kwargs['lam']\n \n # compute principal components\n V,D = compute_pcs(X,lam)\n V = V[:,-num_components:]\n D = D[-num_components:]\n\n # compute transformed data for PC space: V^T X\n W = np.dot(V.T,X)\n return W,V,D\n \ndef PCA_sphere(X,**kwargs):\n '''\n A function for producing the full PCA sphereing on an input dataset X. \n '''\n # compute principal components\n W,V,D = pca_transform_data(X,**kwargs)\n \n # compute transformed data for PC space: V^T X\n W = np.dot(V.T,X)\n D_ = np.array([1/d**(0.5) for d in D])\n D_ = np.diag(D_)\n S = np.dot(D_,W)\n return W,S\n\ndef ZCA_sphere(X,**kwargs):\n '''\n A function for producing the full PCA sphereing on an input dataset X. \n ''' \n \n # compute principal components\n W,V,D = pca_transform_data(X,**kwargs)\n \n # PCA-sphere data\n W = np.dot(V.T,X)\n D_ = np.array([1/d**(0.5) for d in D])\n D_ = np.diag(D_)\n S = np.dot(D_,W)\n \n # rotate data back to original orientation - ZCA sphere\n Z = np.dot(V,S)\n \n return W,S,Z\n\n########## plotting functionality ############\ndef show_images(X):\n '''\n Function for plotting input images, stacked in columns of input X.\n '''\n # plotting mechanism taken from excellent answer from stack overflow: https://stackoverflow.com/questions/20057260/how-to-remove-gaps-between-subplots-in-matplotlib\n plt.figure(figsize = (9,3))\n gs1 = gridspec.GridSpec(5, 14)\n gs1.update(wspace=0, hspace=0.05) # set the spacing between axes. \n \n # shape of square version of image\n square_shape = int((X.shape[0])**(0.5))\n\n for i in range(min(70,X.shape[1])):\n # plot image in panel\n ax = plt.subplot(gs1[i])\n im = ax.imshow(255 - np.reshape(X[:,i],(square_shape,square_shape)),cmap = 'gray')\n\n # clean up panel\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n plt.show()","sub_path":"mlrefined_libraries/unsupervised_library/PCA_functionality.py","file_name":"PCA_functionality.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"465917651","text":"from os import error\nfrom PIL import Image\nfrom quantize import quantize\nfrom pathlib import Path\n\ndef parameterization():\n img = Image.open(\"./demoInput.jpg\")\n pixels = img.load()\n dims = img.size\n\n minCellDims = [8, 8]\n\n if(dims[0] != dims[1]):\n error(\"The code currently only works for sqaure images.\")\n for minCellDims in [ [4, 4], [6, 6], [10, 10] ]:\n for thresh in [ 6900, 42000, 420000, 690000 ]:\n for edgeType in [ \"inv\", \"black\", \"white\", \"darken\", \"lighten\" ]:\n print(\"{e} | {t} | {w}x{h}\".format(e=edgeType, t=thresh, w=minCellDims[0], h=minCellDims[1]))\n\n out = Image.new(mode=\"RGB\", size=dims)\n quantize(\n cell=[ 0, 0, dims[0], dims[1] ], \n inputPixels=pixels, \n outputImage=out, \n thresh=thresh, \n minCellDims=minCellDims,\n showEdges=True, \n edgeType=edgeType\n )\n path = Path(\"./demoOut/out_{thresh}_{edge}_min{w}x{h}.png\".format(thresh=thresh, edge=edgeType, w=minCellDims[0], h=minCellDims[1]))\n out.save(path)\n out.close()\n\ndef test():\n img = Image.open(\"./laikka.jpg\")\n pixels = img.load()\n dims = img.size\n\n minCellDims = [6, 6]\n\n thresh = 69420\n\n for edgeType in [ \"inv\", \"black\", \"white\" ]:\n out = Image.new(mode=\"RGB\", size=dims)\n quantize(\n cell=[ 0, 0, dims[0], dims[1] ], \n inputPixels=pixels, \n outputImage=out, \n thresh=thresh, \n minCellDims=minCellDims,\n showEdges=True, \n edgeType=edgeType\n )\n path = Path(\"./demoOut/out_{thresh}_{edge}_min{w}x{h}.png\".format(thresh=thresh, edge=edgeType, w=minCellDims[0], h=minCellDims[1]))\n out.save(path)\n out.close()\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"586819982","text":"###################################################################################\n# pop uo three new windows, with style\n# destroy() kills one window, quit() kill all windows and app; top-level\n# windows have title, icon, iconify/deconify and protocol for wm events;\n# there always is an app root window, whether by default or created as an\n# explicit Tk object; alll top-level windows are containers, but never\n# packed/gridded; Toplevel is like frame, but new windows, and can have menus;\n###################################################################################\n\nfrom Tkinter import *\nfrom tkSimpleDialog import askstring\n\ndef getName():\n label = askstring('Would you kindly', 'Enter your name?: ')\n root.title(label)\n\nroot = Tk() # exlicit root\nname = 'Phillip'\n\n# win = Toplevel(root) \n# win.title(name) \n\n\nmsg = Button(root, text=name, command=getName)\nmsg.pack(expand=YES, fill=BOTH)\nmsg.config(padx=10, pady=10, bd=10, relief=RAISED)\nmsg.config(bg='black', fg='white', font=('times', 30, 'bold italic'))\n\nroot.mainloop()\n","sub_path":"Python/ProgramPython/c9/experiment/askForNameGUI.py","file_name":"askForNameGUI.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"554881153","text":"array = [1, 3, 9, 8, 2, 7, 5]\n\niCount = 0\n\ndef iSort(arr, start, end):\n global iCount\n for i in range(start + 1, end + 1):\n j = i \n while(j > 0 and arr[j - 1] > arr[j]):\n \n j -= 1\n iCount = iCount + 1\n arr[j + 1] = key\n \n return arr\n \niSort(array, 0, 6)\n\nprint(array)\n","sub_path":"Insertion_sort.py","file_name":"Insertion_sort.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"602790854","text":"# https://www.hackerrank.com/challenges/candies/problem\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the candies function below.\ndef candies(n, arr):\n toffee = [0]*n\n\n # forward pass\n toffee[0] = 1\n for i in range(1, n):\n if(arr[i] > arr[i-1]):\n toffee[i] = toffee[i-1] + 1\n else:\n toffee[i] = 1\n\n # backward pass\n for i in range(n-2, -1, -1):\n if(arr[i] > arr[i+1]):\n toffee[i] = max(toffee[i+1] + 1, toffee[i])\n \n # count the total toffees\n total = 0\n for i in range(n):\n total += toffee[i]\n\n return total\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n arr = []\n\n for _ in range(n):\n arr_item = int(input())\n arr.append(arr_item)\n\n result = candies(n, arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"Hackerrank/Array/Candies.py","file_name":"Candies.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"434101355","text":"from sys import stdin\ndef solve(l):\n if len(l)%2 !=0:\n print((l[len(l)//2])/1)\n else:\n print((l[len(l)//2] + l[(len(l)//2)-1])/2)\ndef main():\n n,l= int(stdin.readline().strip()), []\n for elm in range(n):\n m= int(stdin.readline().strip())\n l.append(m)\n l.sort()\n solve(l)\nmain()\n","sub_path":"laboratorios/Lab-9/B/2_.py","file_name":"2_.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"17459495","text":"\"\"\"\nWAR CARD GAME\n\"\"\"\nfrom random import shuffle\n\ncolors=(\"Spades\",\"Hearts\",\"Clubs\",\"Diamonds\")\nfigures=(\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\",\"Jack\",\"Queen\",\"King\",\"Ace\")\ncards_and_values={'Two':2,\"Three\":3,\"Four\":4,\"Five\":5,\"Six\":6,\"Seven\":7,\"Eight\":8,\"Nine\":9,\\\n\"Ten\":10,\"Jack\":11,\"Queen\":12,\"King\":13,\"Ace\":14}\n\nclass Card():\n \"\"\"\n Class CARD\n \"\"\"\n def __init__(self,color_card,figure):\n self.color_card=color_card\n self.figure=figure\n self.value = cards_and_values[figure]#value of card,the higher card has higher the value\n\n def __str__(self):\n return f\"{self.figure} {self.color_card}\"\n\n def __repr__(self):\n return self.__str__()\n\nclass Deck():\n \"\"\"\n CLASS DECK\n \"\"\"\n def __init__(self):\n self.all_of_cards =[]\n #how many cards are in the deck\n def __len__(self):\n \"\"\"\n how many cards are in the deck\n \"\"\"\n return len(self.all_of_cards)\n\n def create_deck_of_cards(self):\n \"\"\"\n create deck\n \"\"\"\n for color_card in colors :\n for card_figure in figures:\n new_card=Card(color_card,card_figure)\n self.all_of_cards.append(new_card)\n \"\"\"\n for unit test add new method\n \"\"\"\n def add_cards_to_deck(self,deck):\n self.all_of_cards.extend(deck)\n\n def shuffle(self):\n \"\"\"\n shuffle deck\n \"\"\"\n shuffle(self.all_of_cards)\n\nclass Player():\n \"\"\"\n CLASS PLAYER\n \"\"\"\n def __init__(self,name):\n self.name=name\n self.cards=[]\n\n def __str__(self):\n return f\"Player {self.name} has {len(self.cards)}\"\n\n def add_cards(self,new_cards):\n \"\"\"\n add cards to player's deck\n \"\"\"\n if isinstance(new_cards,type([])):\n self.cards.extend(new_cards)\n else:\n self.cards.append(new_cards)\n\n def remove_cards(self,card_number):\n \"\"\"\n remove cards from player's deck\n \"\"\"\n del self.cards[0:card_number+1]\n\n\ndef main(set_of_cards):\n \"\"\"\n main function\n \"\"\"\n player_one=Player(\"One\")#create player\n player_two=Player(\"Two\")#create player\n my_deck=Deck()\n my_deck.add_cards_to_deck(set_of_cards)\n player_one.cards=my_deck.all_of_cards[:3]#split deck\n player_two.cards=my_deck.all_of_cards[3:6]#split deck\n print(\"Start a game:\")\n game_on=True\n war_round=1\n result=0\n #GAME START\n while game_on:#check game on\n #Check if player one's deck is empty\n #if player one's deck is empty, player 2 will win\n if len(player_one.cards)==0:\n print(\"Congratulions. Win player 2\")\n result=2\n break\n #Check if player second's deck is empty\n #if it is empty, player 1 will win\n if len(player_two.cards)==0:\n print(\"Congratulions. Win player 1\")\n result=1\n break\n\n print(f\"{war_round} round\")\n\n card_index=0\n #if first player's card is equal to second player's card\n #there is war and check next cards until if any of player win round\n #counter is incremented by 2,because we check every second card\n while card_index<26:\n #Battle\n if card_index>=2:#if value of player one's cards is equal to value of player two a draw, it will be War\n print(\"War\")\n if player_one.cards[card_index].value > player_two.cards[card_index].value: #if player one's card is better than player two's card\n player_one.remove_cards(card_index+1)\n player_two.remove_cards(card_index+1)\n player_one.add_cards(player_one.cards[:card_index+1])\n player_one.add_cards(player_two.cards[:card_index+1])\n print(f\"Win player 1 in the {war_round} round\")\n break\n elif player_one.cards[card_index].value < player_two.cards[card_index].value:#if player two's card is better than player one's card\n player_one.remove_cards(card_index+1)\n player_two.remove_cards(card_index+1)\n player_two.add_cards(player_two.cards[:card_index+1])\n player_two.add_cards(player_one.cards[:card_index+1])\n print(f\"Win player 2 in the {war_round} round\")\n break\n else:#if there is draw\n #check how many cards player 1 has\n #if he has less than 3 cards,he loses\n if len(player_one.cards)<3:\n print(\"Player One unable to declare war\")\n print(\"Congratulions. Win player 2\")\n game_on=False\n result=2\n break\n #check how many cards player 2 has\n #if he has less than 3 cards,he loses\n if len(player_two.cards)<3:\n print(\"Player Two unable to declare war\")\n print(\"Congratulions. Win player 1\")\n game_on=False\n result=1\n break\n #if players have more than 3 cards\n #players will take next cards and check the following value of cards again\n else:\n card_index+=2\n continue\n war_round+=1\n return result\n\ncards=[Card(\"Spades\",\"Ten\"),Card(\"Hearts\",\"Nine\"),Card(\"Clubs\",\"Eight\"),\\\n Card(\"Hearts\",\"Seven\"),Card(\"Clubs\",\"Six\"),Card(\"Clubs\",\"Five\")]\nmain(cards)\n","sub_path":"war_card_game_code_to_unit_test.py","file_name":"war_card_game_code_to_unit_test.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"596249841","text":"import math\nimport random\nimport libpyDirtMP as prx\n\n\nprx.init_random(random.randint(1,999999))\nacrobot = prx.two_link_acrobot(\"acrobot\")\nsimulation_step = 0.01\nprx.set_simulation_step(simulation_step)\nprint(\"Using simulation_step:\", simulation_step)\n\nstart_state = [0, 0, 0, 0]\ngoal_state = [math.pi, 0, 0, 0]\n\n\nobs_pose_1 = prx.transform()\nobs_pose_2 = prx.transform()\nobs_pose_3 = prx.transform()\nobs_pose_4 = prx.transform()\nobs_pose_1.setIdentity()\nobs_pose_2.setIdentity()\nobs_pose_3.setIdentity()\nobs_pose_4.setIdentity()\nobs_pose_1.translation(prx.vector( 20, 20,0.5))\nobs_pose_2.translation(prx.vector(-20, 20,0.5))\nobs_pose_3.translation(prx.vector( 20,-20,0.5))\nobs_pose_4.translation(prx.vector(-20,-20,0.5))\nb1 = prx.box.create_obstacle(\"b1\", 1., 1., 1., obs_pose_1)\nb2 = prx.box.create_obstacle(\"b2\", 1., 1., 1., obs_pose_2)\nb3 = prx.box.create_obstacle(\"b3\", 1., 1., 1., obs_pose_3)\nb4 = prx.box.create_obstacle(\"b4\", 1., 1., 1., obs_pose_4)\n\nobstacles = [b1, b2, b3, b4]\nobs_names = [\"b1\", \"b2\", \"b3\", \"b4\"]\n### To have an obstacle-free environment, uncomment the following lines (and comment the above)\n# obstacles = []\n# obs_names = []\nwm = prx.world_model([acrobot], obstacles)\nwm.create_context(\"context\", [\"acrobot\"], obs_names)\ncontext = wm.get_context(\"context\");\n\nplanner = prx.dirt(\"dirt\");\nplanner_spec = prx.dirt_specification(context.system_group,context.collision_group);\nplanner_spec.blossom_number = 5\nplanner_spec.use_pruning = False\n\n\ndef acrobot_distance_function(s1, s2):\n\tcost = 0\t\n\ts1a0 = s1[0] + prx.PRX_PI\n\ts1a1 = s1[1] + prx.PRX_PI\n\ts1a2 = s1[2] \n\ts1a3 = s1[3] \n\t\t\n\ts2a0 = s2[0] + prx.PRX_PI\n\ts2a1 = s2[1] + prx.PRX_PI\n\ts2a2 = s2[2] \n\ts2a3 = s2[3] \n\n\ta0 = min((2 * prx.PRX_PI) - abs(s1a0 - s2a0), abs(s1a0 - s2a0));\n\ta1 = min((2 * prx.PRX_PI) - abs(s1a1 - s2a1), abs(s1a1 - s2a1));\n\ta2 = s1a2 - s2a2;\n\ta3 = s1a3 - s2a3;\n\n\tcost = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3\n\n\treturn math.sqrt(cost);\n\nplanner_spec.distance_function = prx.distance_function.set_df(acrobot_distance_function);\n\nplanner_spec.min_control_steps = 1\nplanner_spec.max_control_steps = 50\n\n# planner_spec.random_seed = random.randint(1,999999);\nplanner_spec.bnb = True;\n\nplanner_query = prx.dirt_query(context.system_group.get_state_space(),context.system_group.get_control_space());\nplanner_query.start_state = context.system_group.get_state_space().make_point()\nplanner_query.goal_state = context.system_group.get_state_space().make_point()\ncontext.system_group.get_state_space().copy_point_from_vector(planner_query.start_state, start_state);\ncontext.system_group.get_state_space().copy_point_from_vector(planner_query.goal_state, goal_state);\n\nprint(\"Start State:\", planner_query.start_state)\nprint(\"Goal State:\", planner_query.goal_state)\n\nplanner_query.goal_region_radius = 0.5;\nplanner_query.get_visualization = True;\n\nplanner.link_and_setup_spec(planner_spec)\nplanner.preprocess()\nplanner.link_and_setup_query(planner_query)\n\n### Note: Python slows down computation ==> more time might be needed\n# checker = prx.condition_check(\"time\", 60)\nchecker = prx.condition_check(\"iterations\", 50000)\n\nprint(\"Resolving query...\")\nplanner.resolve_query(checker)\nplanner.fulfill_query();\n\n\n### This part is only to visualize the solution\nif (planner_query.get_visualization):\n\tvis_group = prx.three_js_group([acrobot], obstacles)\n\tif ( len(planner_query.solution_traj) != 0 ) :\n\t\tvis_group.add_vis_infos(prx.info_geometry.FULL_LINE, planner_query.solution_traj, \"acrobot/ball\", context.system_group.get_state_space(), \"0x000000\");\n\n\ttimestamp = 0.0\n\tfor state in planner_query.solution_traj :\n\t\tcontext.system_group.get_state_space().copy_from_point(state);\n\t\tvis_group.snapshot_state(timestamp)\n\t\ttimestamp += simulation_step\n\n\tvis_group.output_html(\"py_output.html\");\n","sub_path":"examples/basic/acrobot/dirt.py","file_name":"dirt.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"490928276","text":"from setuptools import setup, find_packages\r\nimport redpic\r\n\r\nwith open(\"README.md\", \"r\") as fh:\r\n long_description = fh.read()\r\n\r\nsetup(\r\n name='redpic',\r\n version=redpic.__version__,\r\n author='Vyacheslav Fedorov',\r\n author_email='fuodorov1998@gmail.com',\r\n description=redpic.__doc__,\r\n long_description=long_description,\r\n long_description_content_type=\"text/markdown\",\r\n url='https://github.com/fuodorov/redpic',\r\n packages=find_packages(),\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Operating System :: OS Independent\",\r\n 'Intended Audience :: Science/Research',\r\n 'Topic :: Scientific/Engineering :: Physics'\r\n ],\r\n python_requires='>=3.6',\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"290860852","text":"import string\nimport random\nimport subprocess\n\nword_list = subprocess.check_output(\n \"cat /usr/share/dict/words | grep -v \\\"'s\\\"\",\n shell=True, \n universal_newlines=True\n).split('\\n')\n\n# word_list = ['munchkin', 'cat', 'vex', 'dog', 'doom', 'aardvark', 'recursion', 'dyslexia']\n\nword = random.choice(word_list).upper()\nblanks = [\"_\"] * len(word)\navailable_guesses = 10\nnum_bad_guess = 0\nplayer_guesses = []\nwinner = False\n\n\ndef get_input():\n invalid = True\n while invalid:\n print(\"You have guessed: {}\".format(', '.join(sorted(player_guesses)) if player_guesses else ''))\n guess = input(\"Guess letter: \").upper()\n if len(guess) > 1:\n print(\"Only guess one letter, dummy.\")\n elif guess in player_guesses:\n print(\"You've already guessed that letter, dummy.\")\n elif guess not in string.ascii_letters:\n print(\"Enter only letters, dummy.\")\n else:\n invalid = False\n return guess\n\n\nwhile num_bad_guess < available_guesses and not winner:\n\n print('\\n({} letters)\\t{}'.format(len(word), ''.join(blanks)))\n \n guess = get_input()\n player_guesses.append(guess)\n\n if guess in word.upper(): \n print(\"You guessed right\")\n indecies = [pos for pos, char in enumerate(word) if char == guess]\n for index in indecies:\n blanks[index] = guess\n else:\n print(\"You guessed wrong\")\n num_bad_guess += 1\n print(\"You've made {}/{} wrong guesses\".format(num_bad_guess, available_guesses))\n\n if ''.join(blanks).upper() == word.upper():\n winner = True\n\nif winner: \n print(\"You have guessed the word! {}\".format(word))\nelse:\n print(\"You lose! The word was {}\".format(word))\n\n\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"462782156","text":"from boa.interop.System.Storage import Put, Get, GetContext\nfrom boa.builtins import concat\n\nfrom boa.interop.System.Storage import Put, Delete\nfrom boa.interop.System.Runtime import CheckWitness, Notify\n\nfrom template_contract_test.libs.SafeCheck import Require, RequireScriptHash,RequireWitness\nfrom template_contract_test.libs.Utils import SafePut\nfrom template_contract_test.libs.SafeMath import Sub, Add\n\n\nTOKEN_NAME = 'My Simple Token'\nTOKEN_SYMBOL = 'MST'\n\n################################################################################\n# TOKEN INFO CONSTANTS\n\n# DEPLOYER is AQf4Mzu1YJrhz9f3aRkkwSm9n3qhXGSh4p---616f2a4a38396ff203ea01e6c070ae421bb8ce2d\nDEPLOYER = bytearray(b'\\x61\\x6f\\x2a\\x4a\\x38\\x39\\x6f\\xf2\\x03\\xea\\x01\\xe6\\xc0\\x70\\xae\\x42\\x1b\\xb8\\xce\\x2d')\n\nINIT_SUPPLY = 1000000000\nTOKEN_DECIMALS = 8\nFACTOR = 100000000\n\n################################################################################\n# STORAGE KEY CONSTANT\n# Belows are storage key for some variable token information.\n\nOWNER_KEY = '___OWNER'\nMST_SUPPLY_KEY = '__SUPPLY'\n\n\n################################################################################\n# STORAGE KEY PREFIX\n# Since all data are stored in the key-value storage, the data need to be\n# classified by key prefix. All key prefixes length must be the same.\n\nOWN_PREFIX = '_____own'\nALLOWANCE_PREFIX = '___allow'\n\n\n################################################################################\n#\n\ndef Main(operation, args):\n if operation == 'deploy':\n return Deploy()\n elif operation == 'name':\n return TOKEN_NAME\n elif operation == 'decimals':\n return TOKEN_DECIMALS\n elif operation == 'symbol':\n return TOKEN_SYMBOL\n elif operation == 'totalSupply':\n return TotalSupply()\n elif operation == 'balanceOf':\n if len(args) == 1:\n return BalanceOf(args[0])\n elif operation == 'transfer':\n if len(args) == 3:\n return Transfer(args[0], args[1], args[2])\n elif operation == 'transferFrom':\n if len(args) == 4:\n return TransferFrom(args[0], args[1], args[2], args[3])\n elif operation == 'approve':\n if len(args) == 3:\n return Approve(args[0], args[1], args[2])\n elif operation == 'allowance':\n if len(args) == 2:\n return Allowance(args[0], args[1])\n elif operation == 'mint':\n if len(args) == 2:\n return Mint(args[0], args[1])\n elif operation == 'burn':\n if len(args) == 1:\n return Burn(args[0])\n elif operation == 'transferOwnership':\n if len(args) == 1:\n return TransferOwnership(args[0])\n\n return False\n\n\ndef Deploy():\n \"\"\"\n Constructor of this contract. Only deployer hard-coded can call this function\n and cannot call this function after called once.\n Followings are initialization list for this token\n 1. Transfer the owner to the deployer. (Owner can mint and burn the token)\n 2. Supply initial coin to the deployer.\n \"\"\"\n ctx = GetContext()\n\n Require(CheckWitness(DEPLOYER)) # only can be initialized by deployer\n Require(not Get(ctx, 'DEPLOYED')) # only can deploy once\n\n # disable to deploy again\n Put(ctx, 'DEPLOYED', 1)\n\n # the first owner is the deployer\n # can transfer ownership to other by calling `transferOwner` function\n Put(ctx, OWNER_KEY, DEPLOYER)\n\n # supply the coin. All coin will belong to deployer.\n Put(ctx, MST_SUPPLY_KEY, INIT_SUPPLY * FACTOR)\n Put(ctx, concat(OWN_PREFIX, DEPLOYER), INIT_SUPPLY * FACTOR)\n\n return True\n\n\ndef TotalSupply():\n \"\"\"\n Gets the total supply for MST token. The total supply can be changed by\n owner's invoking function calls for minting and burning.\n \"\"\"\n return _totalSupply(GetContext())\n\n\ndef BalanceOf(account):\n \"\"\"\n Gets the MST token balance of an account.\n :param account: account\n \"\"\"\n return _balanceOf(GetContext(), account)\n\n\ndef Transfer(_from, _to, _value):\n \"\"\"\n Sends the amount of tokens from address `from` to address `to`. The parameter\n `from` must be the invoker.\n :param _from: invoker address.\n :param _to: receiver address.\n :param _value: MST amount.\n \"\"\"\n RequireWitness(_from) # from address validation\n return _transfer(GetContext(), _from, _to, _value)\n\n\ndef TransferFrom(_originator, _from, _to, _amount):\n \"\"\"\n Transfers the amount of tokens in `from` address to `to` address by invoker.\n Only approved amount can be sent.\n :param _originator: invoker address.\n :param _from: address for withdrawing.\n :param _to: address to receive.\n :param _amount: MST amount.\n \"\"\"\n return _transferFrom(GetContext(), _originator, _from, _to, _amount)\n\n\ndef Approve(_from, _to, _amount):\n \"\"\"\n Approves `to` address to withdraw MST token from the invoker's address. It\n overwrites the previous approval value.\n :param _from: invoker address.\n :param _to: address to approve.\n :param _amount: MST amount to approve.\n \"\"\"\n RequireWitness(_from) # only the token owner can approve\n return _approve(GetContext(), _from, _to, _amount)\n\n\ndef Burn(_amount):\n \"\"\"\n Burns the amount of MST token from the owner's address.\n :param _amount: MST amount to burn.\n \"\"\"\n ctx = GetContext()\n _onlyOwner(ctx) # only owner can burn the token\n return _burn(ctx, Get(ctx, OWNER_KEY), _amount)\n\n\ndef Mint(_to, _amount):\n \"\"\"\n Mints the amount of MST token.\n :param _to: address to receive token.\n :param _amount: the amount to mint.\n \"\"\"\n ctx = GetContext()\n _onlyOwner(ctx) # only owner can mint token\n return _mint(ctx, _to, _amount)\n\n\ndef TransferOwnership(_account):\n \"\"\"\n Transfers the ownership of this contract to other.\n :param _account: address to transfer ownership.\n \"\"\"\n ctx = GetContext()\n _onlyOwner(ctx)\n return _transferOwnership(ctx, _account)\n\n\ndef Allowance(_from, _to):\n \"\"\"\n Gets the amount of allowance from address `from` to address `to`.\n :param _from: from address\n :param _to: to address\n :return: the amount of allowance.\n \"\"\"\n return _allowance(GetContext(), _from, _to)\n\n\n################################################################################\n# INTERNAL FUNCTIONS\n# Internal functions checks parameter and storage result validation but these\n# wouldn't check the witness validation, so caller function must check the\n# witness if necessary.\n\ndef _transfer(_context, _from, _to, _value):\n Require(_value > 0) # transfer value must be over 0\n RequireScriptHash(_to) # to-address validation\n\n from_val = _balanceOf(_context, _from)\n to_val = _balanceOf(_context, _to)\n\n from_val = Sub(from_val, _value)\n to_val = Add(to_val, _value)\n\n SafePut(_context, concat(OWN_PREFIX, _from), from_val)\n SafePut(_context, concat(OWN_PREFIX, _to), to_val)\n\n Notify([\"transfer\", from_val, to_val, _value])\n\n return True\n\n\ndef _balanceOf(_context, _account):\n return Get(_context, concat(OWN_PREFIX, _account))\n\n\ndef _transferFrom(_context, _owner, _spender, _to, _amount):\n RequireWitness(_owner)\n RequireScriptHash(_spender)\n RequireScriptHash(_to)\n\n Require(_amount > 0)\n\n approve_key = concat(ALLOWANCE_PREFIX, concat(_spender, _owner))\n approve_amount = Get(_context, approve_key)\n approve_amount = Sub(approve_amount, _amount)\n\n\n if not _transfer(_context, _spender, _to, _amount):\n return False\n\n SafePut(_context, approve_key, approve_amount)\n\n Notify([\"transferFrom\", _owner, _spender, _to, _amount])\n\n return True\n\n\ndef _approve(_context, _from, _to, _amount):\n RequireScriptHash(_to) # to-address validation\n Require(_amount >= 0) # amount must be not minus value\n\n from_val = _balanceOf(_context, _from)\n approved_val = _allowance(_context, _from, _to)\n approve_val = Add(approved_val, _amount)\n Require(from_val >= approve_val) # the token owner must have the amount over approved\n\n approve_key = concat(ALLOWANCE_PREFIX, concat(_from, _to))\n SafePut(_context, approve_key, approve_val)\n\n return True\n\n\ndef _burn(_context, _account, _amount):\n Require(_amount > 0) # the amount to burn should be over 0\n\n account_val = _balanceOf(_context, _account)\n total_supply = _totalSupply(_context)\n\n Require(_amount < total_supply) # should be not over total supply\n\n # burn the token from account. It also subtract the total supply\n account_val = Sub(account_val, _amount)\n total_supply = Sub(total_supply, _amount)\n\n SafePut(_context, concat(OWN_PREFIX, _account), account_val)\n SafePut(_context, MST_SUPPLY_KEY, total_supply)\n\n Notify([\"burn\", _account, _amount])\n\n return True\n\n\ndef _mint(_context, _to, _amount):\n Require(_amount > 0) # mint value must be over 0\n RequireScriptHash(_to) # to address should\n\n total_supply = _totalSupply(_context)\n to_val = _balanceOf(_context, _to)\n\n # Add total supply value and give the token to the to-address\n total_supply += _amount\n to_val += _amount\n\n SafePut(_context, MST_SUPPLY_KEY, total_supply)\n SafePut(_context, concat(OWN_PREFIX, _to), to_val)\n\n Notify([\"mint\", _to, _amount])\n\n return True\n\n\ndef _transferOwnership(_context, _account):\n RequireScriptHash(_account)\n Put(_context, OWNER_KEY, _account)\n\n Notify([\"transferOwnership\", _account])\n\n return True\n\n\n################################################################################\n# modifiers\n\ndef _onlyOwner(_context):\n \"\"\"\n Checks the invoker is the contract owner or not. Owner key is saved in the\n storage key `___OWNER`, so check its value and invoker.\n \"\"\"\n RequireWitness(Get(_context, OWNER_KEY))\n\n\n################################################################################\n\ndef _totalSupply(_context):\n return Get(_context, MST_SUPPLY_KEY)\n\n\ndef _allowance(_context, _from, _to):\n return Get(_context, concat(ALLOWANCE_PREFIX, concat(_from, _to)))","sub_path":"MySimpleToken/MySimpleToken.py","file_name":"MySimpleToken.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"243530395","text":"import argparse\nimport os\nfrom termcolor import cprint\n\nfrom MidiGenerator.MidiGenerator import MidiGenerator\n\n\ndef main():\n \"\"\"\n Entry point\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Program to train a model over a Midi dataset',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('load', type=str, default='',\n help='The model of the Neural Network ot load')\n parser.add_argument('-d', '--data', type=str, default='lmd_matched_mini',\n help='The name of the data')\n parser.add_argument('--pc', action='store_true', default=False,\n help='to work on a small computer with a cpu')\n parser.add_argument('--gpu', type=str, default='0',\n help='What GPU to use')\n parser.add_argument('-s', '--seed', default=10,\n help='number of seeds or the path to the folder with the seeds')\n parser.add_argument('-l', '--length', type=int, default=20,\n help='The length of the generated music')\n parser.add_argument('-i', '--images', action='store_true', default=False,\n help='Save the images for each instruments')\n parser.add_argument('--no-duration', action='store_true', default=False,\n help='Generate only shortest notes possible')\n parser.add_argument('-v', '--verbose', type=int, default=1,\n help='Level of verbose')\n\n args = parser.parse_args()\n\n if args.pc:\n data_path = os.path.join('../Dataset', args.data)\n args.length = 50\n args.seed = 2\n else:\n data_path = os.path.join('../../../../../../storage1/valentin', args.data)\n data_transformed_path = data_path + '_transformed'\n\n if not args.pc:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n my_model = MidiGenerator.with_model(id=args.load) # Load the model\n my_model.generate_fom_data(length=args.length,\n nb_seeds=args.seed,\n save_images=args.images,\n no_duration=args.no_duration,\n verbose=args.verbose)\n\n cprint('---------- Done ----------', 'grey', 'on_green')\n\n\nif __name__ == '__main__':\n # create a separate main function because original main function is too mainstream\n main()\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"565898032","text":"subs = {\n 'all' : [ ## Special key: Changes are applied to all applicable conversions automatically\n [None,None]\n ],\n 'normal' : [ ## Dictionary is keyed on substitution type\n ['s','d'], ## Special Line Indicating type columns\n ('sdot','ddot'),\n ('sgemm','dgemm'),\n ('sgemm_para','dgemm_para'),\n ('sgemv','dgemv'),\n ('sger','dger'),\n ('saxpy','daxpy'),\n ('smut','dmut'),\n ('shandler','dhandler'),\n ('float','double'),\n ],\n};\n","sub_path":"TDP1/src_blas/subs.py","file_name":"subs.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"287522974","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import Http404\nfrom PIL import Image, ImageFont, ImageDraw\nimport random\nimport sys\n\n# Create your views here.\n\n\ndef rmdRGB():\n c1 = random.randrange(0, 255)\n c2 = random.randrange(0, 255)\n c3 = random.randrange(0, 255)\n return c1, c2, c3\n\n\ndef verify_code(request):\n bgcolor = '#997679'\n width = 100\n height = 25\n # 创建画布\n im = Image.new('RGB', (width, height), bgcolor)\n # 创建画笔\n draw = ImageDraw.Draw(im)\n # 画点\n for i in range(0, 100):\n xy = (random.randrange(0, width), random.randrange(0, height))\n fill = (random.randrange(0, 255), 255, random.randrange(0, 255))\n draw.point(xy, fill=fill)\n\n # 添加干扰线\n for i in range(8):\n x1 = random.randrange(0, width)\n y1 = random.randrange(0, height)\n x2 = random.randrange(0, width)\n y2 = random.randrange(0, height)\n draw.line((x1, y1, x2, y2), fill=rmdRGB())\n # 添加圆\n\n # 写字\n str1 = '123456789abcdefghijkmnpgrstuvwxyzABCDEFJHJKLMNPQRSTUVWXYZ'\n rand_str = ''\n for i in range(0, 4):\n rand_str += str1[random.randrange(0, len(str1))]\n\n # 字体\n # font = ImageFont.truetype('/usr/share/fonts/truetype/fonts-japanese-gothic',23)\n # 判断是什么操作系统(操作系统兼容)\n if sys.platform == 'linux':\n font = ImageFont.truetype(\n '/usr/share/fonts/truetype/fonts-japanese-gothic', 23)\n elif sys.platform == 'darwin': # Mac OS X\n font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 23)\n elif sys.platform == 'win32':\n font = ImageFont.truetype(r'C:\\Windows\\Fonts\\arial.ttf', 23)\n else:\n raise Http404(\"暂不支持此操作系统: \" + sys.platform)\n\n # 构造字体颜色\n fontcolors = ['yellow', 'blue', 'green', 'red', 'orange', 'pink']\n\n draw.text((5, 2), rand_str[0], fill=random.sample(fontcolors, 1)[0], font=font)\n draw.text((25, 2), rand_str[1], fill=random.sample(fontcolors, 1)[0], font=font)\n draw.text((45, 2), rand_str[2], fill=random.sample(fontcolors, 1)[0], font=font)\n draw.text((70, 2), rand_str[3], fill=random.sample(fontcolors, 1)[0], font=font)\n\n # 结束\n del draw\n # 存入session\n request.session['verifycode'] = rand_str\n print('verifycode', request.session['verifycode'])\n # 内存文件操作\n import io\n # 获得一个内存缓存区\n buf = io.BytesIO()\n # 将图片保存在缓存区,格式为png\n im.save(buf, 'png')\n # 将缓存区的内容返回给前端 .getvalue 是把缓存区的所有数据读取\n return HttpResponse(buf.getvalue(), 'image/png')\n","sub_path":"verify/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"601946962","text":"#-*-coding:utf-8 -*-\n# from framework.testApiWay import *\nfrom framework.readExcel import ReadExcel\nimport unittest\nfrom framework import readConfigFile\nfrom framework.logger import Logger\n\nfrom framework.testApiUpdate import testApi\nfrom common.login import test_Login_token\nconfig = readConfigFile.ReadConfig()\n# token=config.get_http(\"token\")\n# login = test_login()\n# token = login.test_Login_token()\nmylog = Logger(logger=\"test_AddLuckys\").getlog()\n\n\n\n\nclass test_AddLuckys(unittest.TestCase):\n '''接口名称:发布幸运红包'''\n\n def setUp(self):\n print(\"测试开始\")\n pass\n\n\n def test_AddLucky(self):\n \"\"\"\n 幸运红包\n :return:\n\n \"\"\"\n token = test_Login_token()\n print(token)\n excel = ReadExcel(\"幸运红包\")\n\n\n data = excel.getData\n state_code = excel.getStatusCode\n\n\n\n\n url = excel.getUrl\n print(url)\n method = excel.getMethod\n\n row = excel.getRows\n buer=excel.getEncryption\n status=excel.getStatus\n t = testApi()\n\n\n for i in range(0, row - 1):\n if status[i]=='执行':\n dict_data = eval(data[i])\n buer_i = int(buer[i])\n result = t.http_request(url=url[i], method=method[i], token=token, encryption=buer_i, **dict_data)\n print(result)\n self.assertEqual(result['message'], state_code[i])\n\n # print(type(result))\n\n if result['message'] == state_code[i]:\n RESULT = 'PASS'\n else:\n RESULT = 'FAIL'\n\n excel.result_write(str(RESULT))\n else:\n print('你规定不执行')\n\n\n\n mylog.info(\"测试完成\")\n\nif __name__=='__main__':\n unittest.main(verbosity=2)","sub_path":"testCase/test_add_lucky_D.py","file_name":"test_add_lucky_D.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"542129895","text":"from math import * \nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\nfrom Samecolor import *\nfrom Color import *\nfrom hgm import *\nfrom featurename import *\n\nclass ClusterModel():\n def __init__(self):\n self.count = 0\n self.data = []\n self.timeent = []\n self.header = None\n self.gmm = False\n self.prior = False\n self.lasty = [0]\n self.perm = {0:0}\n self.changed = False\n self.version = -1\n self.type = 'ClusterModel'\n self.featurename1 = 'ClusterIndex'\n self.featurename2 = 'ClusterAnomaly'\n self.index_attribute = False\n self.time_attribute = False\n self.entity_attribute = False\n self.maxsplit = 1\n\n def dictaddindex(self, vec, dic):\n res = {}\n if self.time_attribute:\n res[self.time_attribute] = vec[self.time_attribute]\n else:\n res[self.index_attribute] = vec[self.index_attribute]\n if self.entity_attribute:\n res[self.entity_attribute] = vec[self.entity_attribute]\n res.update(dic)\n return res\n\n def indexvalues(self, vec):\n return tuple([vec[a] for a in self.indexattrs()])\n\n def indexattrs(self):\n return ([self.index_attribute if not self.time_attribute else self.time_attribute] +\n ([self.entity_attribute] if self.entity_attribute else []))\n\n def reset_data(self):\n self.count = 0\n self.data = []\n self.timeent = []\n self.header = None\n\n def handle_data(self, vecdict):\n if self.header is None:\n self.header = [key for key in vecdict if key not in self.indexattrs()]\n form = { col : ContForm(0,0) for col in self.header}\n self.gmm = MixtureModel(GaussianModel(self.header, form), 1)\n self.prior = MixturePrior(self.gmm, 1.0, form, pd.DataFrame(columns=self.header))\n self.gmm.estimate_init(self.prior)\n vec = pd.DataFrame([vecdict]).iloc[0]\n self.data.append(vec)\n self.timeent.append(self.indexvalues(vecdict))\n self.gmm.estimate_incr(vec, 1.0)\n self.count += 1\n # at regular intervals, call update_model\n if self.count % 200 == 50:\n self.maxsplit = 1\n self.update_model()\n return self.dictaddindex(vecdict,\n {self.featurename1: self.perm[self.maxindex(vec)],\n self.featurename2: self.anomaly(vec)})\n\n def handle_batch_data(self, dt):\n if len(dt) > 0:\n newdata = pd.DataFrame(dt)\n self.data += [newdata.iloc[i] for i in range(len(newdata))]\n self.timeent += [self.indexvalues(newdata.iloc[i]) for i in range(len(newdata))]\n self.count += len(newdata)\n if self.header is None:\n self.header = [key for key in dt[0] if key not in self.indexattrs()]\n form = { col : ContForm(0,0) for col in self.header}\n self.gmm = MixtureModel(GaussianModel(self.header, form), 1)\n self.prior = MixturePrior(self.gmm, 1.0, form, pd.DataFrame(self.data, columns=self.header))\n self.gmm.estimate_init(self.prior)\n self.maxsplit = 6\n self.update_model()\n return [self.dictaddindex(newdata.iloc[i],\n {self.featurename1: self.perm[self.maxindex(newdata.iloc[i])],\n self.featurename2: self.anomaly(newdata.iloc[i])}) for i in range(len(newdata))]\n else:\n return None\n\n def model_type(self):\n return self.type\n\n def model_version(self):\n return self.version\n\n def extract_model(self):\n if self.gmm is not False:\n mod = [{ 'prob':p, 'mean':m.mean, 'var':m.var} for m,p in zip(self.gmm.models,self.gmm.probs)]\n else:\n mod = []\n return { 'type': self.type,\n 'version': self.version,\n 'mixture': mod }\n\n def features_changed(self):\n return self.changed\n\n def maxindex(self, sample):\n if len(self.gmm.models) == 1:\n return 0\n else:\n v = [m.logprobability(sample) + log(p) for m,p in zip(self.gmm.models,self.gmm.probs)]\n return v.index(max(v))\n\n def anomaly(self, sample):\n #if self.gmm.count < 2*len(sample):\n if self.version < 0: # initialized\n return 0.0\n else:\n ano = self.gmm.anomaly(sample)\n return min(1.0, max(0.0, (ano - 14.0)/36.0))\n\n def update_features(self):\n self.changed = False\n y = [self.maxindex(v) for v in self.data]\n z = [self.anomaly(v) for v in self.data]\n ia = self.indexattrs()\n return [self.dictaddindex(dict(zip(ia, te)),\n {self.featurename1: self.perm[yy],\n self.featurename2: zz}) for (te,yy,zz) in zip(self.timeent, y, z)] \n \n def default_params(self):\n return { 'index_attribute': False,\n 'time_attribute': False,\n 'entity_attribute': False}\n\n def set_params(self, dic):\n #if 'num_components' in dic:\n # self.numcomp = dic['num_components']\n if 'time_attribute' in dic:\n self.time_attribute = dic['time_attribute']\n if 'index_attribute' in dic:\n self.index_attribute = dic['index_attribute']\n if 'entity_attribute' in dic:\n self.entity_attribute = dic['entity_attribute']\n\n #----------------------------\n\n def update_model(self):\n def smaxind(ss, i):\n v = [ss[j][i] for j in range(len(ss))]\n return v.index(max(v))\n # check if split, if so run em\n df = pd.DataFrame(self.data, columns= self.header)\n if not self.gmm.initialized:\n ss = self.gmm.init_ss(df, False)\n mod.initialized = True\n else:\n ss = self.gmm.get_ss(df, False)\n # ok rebuild the prior\n self.prior = MixturePrior(self.gmm, 1.0, self.gmm.form, df)\n #print(\"Old: \", self.gmm.models[0].mean, self.gmm.models[0].var)\n ss = self.gmm.estimate_ss(df, False, self.prior, ss, 20, 0.001)\n #print(\"New: \", self.gmm.models[0].mean, self.gmm.models[0].var)\n loop = 0\n while loop < self.maxsplit:\n sigs = []\n if self.time_attribute is not False:\n scales = [feature_scale(n) for n in self.header]\n maxtimescale = max(scales) if scales else 15.0\n tmmd = 4*maxtimescale\n print(\"Gamma timescale:\", tmmd)\n else:\n tmmd = nan\n for i in range(len(ss)):\n sigs.append(gammatest_ts(self.gmm.models[i], ss[i], df, self.timeent, 4000, tmmd))\n print(\"Gamma sigs: \", sigs)\n mx = min(sigs)\n if mx < 0.001:\n ss = self.gmm.split(sigs.index(mx), ss)\n if len(df) > 1600*len(ss):\n ss = self.gmm.estimate_ss_sample(df, False, self.prior, ss, 800*len(ss), 60, 0.0001)\n else:\n ss = self.gmm.estimate_ss(df, False, self.prior, ss, 80, 0.0001)\n y = [smaxind(ss,i) for i in range(len(self.data))]\n self.perm = samecolor(self.lasty, y, self.perm)\n self.lasty = y\n loop += 1\n else:\n loop = self.maxsplit\n if len(df) > 1600*len(ss):\n ss = self.gmm.estimate_ss(df, False, self.prior, ss, 40, 0.0001)\n self.version += 1\n self.changed = True\n \n\ndef gammatest_ts(comp, weights, data, timeent, num, tsmindist):\n # set up vector for quicker search\n # (select first sample)\n # a large number of times\n # select random sample\n # calculate normalized distance from last sample\n # sort distances\n # express expected gamma parameters\n # find the distance at which deviation from expected distr is largest\n # compute its significane level\n data = data[comp.feet]\n dim = len(comp.feet)\n acc = np.cumsum(weights)\n dists = [False]*num\n ps = [False]*num\n oldind = selectind(acc)\n ind = oldind\n wsum = 0\n anum = 0\n if acc[-1] < 10.0 or len(data) < 2*sqrt(num) or (not isnan(tsmindist) and (timeent[-1][0] - timeent[0][0]) < tsmindist):\n return 1.0\n for i in range(num):\n while ind == oldind:\n ind = selectind(acc)\n if isnan(tsmindist) or (len(timeent[ind]) >= 2 and timeent[ind][1] != timeent[oldind][1]) or abs(timeent[ind][0] - timeent[oldind][0]) >= tsmindist:\n dist = sqvec(np.matmul(comp.ilower, np.subtract(data.iloc[ind], data.iloc[oldind])))\n w = weights[oldind] # Because weights[ind] is already accounted for in selection\n dists[i] = (dist, w)\n wsum += w\n anum += 1\n else:\n dists[i] = (inf, 0.0)\n oldind = ind\n dists.sort(key = lambda pr:pr[0])\n mnval = 0\n mnind = 0\n w = 0\n for i in range(anum):\n (d, w0) = dists[i]\n w += w0\n p = gammainc(dim/2, d/4)\n ps[i] = p\n # print((wsum, w, p))\n val = log(wsum*p/w)*w + log(wsum*(1-p)/(wsum-w))*(wsum-w) if p > 0 and p < 1 and w > 0 and w < wsum else 0\n dists[i] = (d, w) \n if val0.05 and p*wsum > w:\n mnval = val\n mnind = i\n (d, w) = dists[mnind]\n p = ps[mnind] #gammainc(dim/2, d/4)\n if mnval == 0:\n sig = 1.0\n elif w > wsum*p:\n n = ceil(w)\n nn = ceil(wsum)\n sig = binom.cdf((nn-n), nn, (1-p))\n else:\n n = floor(w)\n nn = ceil(wsum)\n sig = binom.cdf(n, nn, p)\n\n #plt.figure(2)\n #plt.axes().clear()\n #plt.plot([dists[i][0] for i in range(anum)],[dists[i][1] for i in range(anum)])\n #plt.plot([dists[i][0] for i in range(anum)],[ps[i]*wsum for i in range(anum)])\n \n return sig\n\n\n","sub_path":"bidaf/cluster_model.py","file_name":"cluster_model.py","file_ext":"py","file_size_in_byte":10026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"274789833","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 6 10:41:53 2018\n\n@author: stevechen\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport math\n\n# Read file to get wanted variables from the Airbnb data set\ndef Get_Airbnb_Data(filename):\n data=pd.read_csv(filename,sep=',')\n newdata_df=pd.DataFrame({'price':data['price'],'property_type':data['property_type'],\n 'room_type':data['room_type'],'accommodates':data['accommodates'],\n 'bathrooms':data['bathrooms'],'bedrooms':data['bedrooms'],\n 'beds':data['beds'],'bed_type':data['bed_type'],\n 'guests_included':data['guests_included'],\n 'host_profile_pic':data['host_has_profile_pic'],'identity_verified':data['host_identity_verified'],\n 'zipcode':data['zipcode'],'latitude':data['latitude'],'longitude':data['longitude']})\n\n return (newdata_df)\n \n# Calculate the score of cleaness\ndef Score_Cleanliness(data,positive_var_list,integer_var_list,bool_var_list=None):\n \n # Calculate the number of null variables and calculate the percentage of them\n total_num=data.shape[0]*data.shape[1]\n na_num = sum(data.isnull().sum())\n na_percen = na_num/total_num\n \n # Check missing values for each column\n na_num_df=pd.DataFrame({'total':[na_num]})\n for i in list(data.columns.values):\n temp_num=data[i].isnull().sum()\n temp_df=pd.DataFrame({i:[temp_num]})\n na_num_df=pd.concat([na_num_df,temp_df],axis=1) \n\n\n incor_num=0\n # Find all non positive values\n for i in positive_var_list:\n # Let us omit the na and find the incorrect value\n temp=data.loc[~(np.isnan(data[i]))] \n # Find all negative number\n incor_num=incor_num+sum(temp[i].apply(lambda x: x<0))\n \n # Find all non integer value\n for i in integer_var_list:\n # Let us omit the na and negative number,and find the incorrect value\n temp=data.loc[~(np.isnan(data[i]))]\n temp=temp.loc[~(temp[i]<0)] \n # Find all non integer number\n incor_num=incor_num+sum(temp[i].apply(lambda x: math.floor(x) != x))\n \n \n # Find all incorrect value for a bool variable\n if bool_var_list!=None:\n for i in bool_var_list:\n temp=data.loc[~(pd.isnull(data['bedrooms']))]\n incor_num=incor_num+sum(temp[i].apply(lambda x: x != 't' and x != 'f' and x!='true' and x!='false' and x!='1' and x!='0'))\n \n # Calcualte the percentage of incorrect data\n inco_percen = incor_num/total_num\n \n #Calcuate final score\n score_final=100-100*(na_percen+inco_percen)\n \n #print(\"\\nThe total number of NA value in our original data set is: \",na_num, \", and the percentage of it is: \",na_percen)\n #print(\"\\nThe total number of incorrect value in our original data set is: \",incor_num, \", and the percentage of it is: \",inco_percen)\n\n \n return(na_num_df,incor_num,score_final)\n\n# Transform Categorical variables into dummies: \ndef Category_to_Dummy(data,category_var_list):\n for i in category_var_list:\n # Create dummies variables and concatenate them\n dummies=pd.get_dummies(data[i])\n data=pd.concat([data,dummies],axis=1)\n \n # Drop the categorical variable\n data=data.drop([i],axis=1)\n \n return (data)\n\n \n# Glance at the data \ndef Glancing_Data(data):\n pd.set_option('display.max_columns', None)\n print(data.info())\n print(data.describe())\n \n\n# Clean the data\ndef Data_Cleaning(data,positive_var_list,integer_var_list):\n data=data.dropna() \n \n # Drop variables is not positive\n for i in positive_var_list:\n data=data.loc[~(data[i]<0)] \n \n # Drop variables is not integer\n for i in integer_var_list:\n data=data.loc[~(data[i].apply(lambda x: math.floor(x)!= x))]\n \n return(data)\n \n \n# Change upper case into lower case \ndef LowerCase(data,var):\n for i in var:\n data[i]=data[i].str.lower()\n return (data)\n\n\n# Generate new features and check Airbnb Cleanliness\ndef Airbnb_Cleanliness():\n # Read a csv file and store data into a dataframe\n filename=\"Airbnb_listings.csv\"\n airbnb_df=Get_Airbnb_Data(filename)\n \n # Define lists to store columns' names based on their types\n positive_var_list = {'price','bathrooms','bedrooms','beds','guests_included','zipcode','accommodates','latitude'}\n integer_var_list = {'bedrooms','beds','guests_included','zipcode','accommodates'}\n \n bool_var_list = {'host_profile_pic','identity_verified'}\n \n na_num_df,incor_num,score_final=Score_Cleanliness(airbnb_df,positive_var_list,integer_var_list,bool_var_list)\n na_num_df=na_num_df.T.reset_index()\n with open('Missing&Incorrect_Airbnb.txt','w') as f:\n f.write('The missing values for each variable is: \\n')\n na_num_df.to_csv(f, header=True, index=False, sep='\\t', mode='a')\n f.write('\\nThe total number of incorrect values is: {}.\\nThe final score is: {:4.3f}.'\n .format(incor_num,score_final))\n \n category_var_list = {'property_type','room_type','bed_type'}\n airbnb_df=Category_to_Dummy(airbnb_df,category_var_list)\n print(airbnb_df.shape[0])\n return (airbnb_df)\n \n \n#Check Hotel prices data Cleanliness \ndef HotelPrice_Cleanliness():\n # Read a csv file and store data into a dataframe\n filename=\"Hotel_prices.csv\"\n data=pd.read_csv(filename,sep=',')\n # Select variables which we need\n hotel_df=pd.DataFrame({'price':data['price'],'hotelName':data['hotelName'],'zipcode':data['postalCode']})\n\n\n # Define lists to store columns' names based on their types\n positive_var_list = {'price'}\n integer_var_list = {}\n \n na_num_df,incor_num,score_final=Score_Cleanliness(hotel_df,positive_var_list,integer_var_list)\n na_num_df=na_num_df.T.reset_index()\n with open('Missing&Incorrect_HotelPrice.txt','w') as f:\n f.write('The missing values for each variable is: \\n')\n na_num_df.to_csv(f, header=True, index=False, sep='\\t', mode='a')\n f.write('\\nThe total number of incorrect values is: {}.\\nThe final score is: {:4.3f}.'\n .format(incor_num,score_final))\n \n \n# Check Yelp Data Cleanliness\ndef YelpData_Cleanliness():\n # Read a csv file and store data into a dataframe\n filename=\"YelpData.csv\"\n data=pd.read_csv(filename,sep=',')\n # Select variables which we need\n hotel_df=pd.DataFrame({'zipcode':data['zipcode'],'rating':data['rating'],'review_count':data['review_count']})\n\n\n # Define lists to store columns' names based on their types\n positive_var_list = {'rating','review_count'}\n integer_var_list = {'review_count','zipcode'}\n \n na_num_df,incor_num,score_final=Score_Cleanliness(hotel_df,positive_var_list,integer_var_list)\n na_num_df=na_num_df.T.reset_index()\n with open('Missing&Incorrect_YelpData.txt','w') as f:\n f.write('The missing values for each variable is: \\n')\n na_num_df.to_csv(f, header=True, index=False, sep='\\t', mode='a')\n f.write('\\nThe total number of incorrect values is: {}.\\nThe final score is: {:4.3f}.'\n .format(incor_num,score_final))\n \n\nif __name__ == \"__main__\":\n # Generate new features and check Airbnb Cleanliness\n airbnb_df=Airbnb_Cleanliness()\n \n #Check Hotel prices data Cleanliness\n HotelPrice_Cleanliness()\n \n # Check Yelp Data Cleanliness\n YelpData_Cleanliness()\n \n\"\"\" \nWe will use below variables for airbnb\n price\n property_type\n room_type\n accommodates\n bathrooms\n bedrooms\n beds\n bed_type\n square_feet \n guests_included\n host_profile_pic\n identity_verified\n zipcode\n latitude\n longitude\n\n\"\"\" \n \n \n ","sub_path":"ANLY501_Project_Part1/DataCleaning-Part1.py","file_name":"DataCleaning-Part1.py","file_ext":"py","file_size_in_byte":7878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"244976167","text":"from time import sleep\nfrom enum import Enum\n\nfrom tron.map import Map, Tile\nfrom tron.player import ACPlayer\nfrom orderedset import OrderedSet\n\nimport torch\nimport random\nimport numpy as np\nimport queue\nfrom config import *\nfrom Net.ACNet import MapNet\n\n\n\nmaptype=type(MapNet())\nclass SetQueue(queue.Queue):\n def _init(self, maxsize):\n self.queue = OrderedSet()\n\n def _put(self, item):\n self.queue.add(item)\n\n def _get(self):\n head = self.queue.__getitem__(0)\n self.queue.remove(head)\n return head\n\n\nclass Winner(Enum):\n PLAYER_ONE = 1\n PLAYER_TWO = 2\n\n\nclass PositionPlayer:\n def __init__(self, id, player, position):\n self.id = id\n self.player = player\n self.position = position\n self.alive = True\n\n def body(self):\n if self.id == 1:\n return Tile.PLAYER_ONE_BODY\n elif self.id == 2:\n return Tile.PLAYER_TWO_BODY\n def slide(self):\n if self.id == 1:\n return Tile.PLAYER_ONE_slide\n elif self.id == 2:\n return Tile.PLAYER_TWO_slide\n\n def head(self):\n if self.id == 1:\n return Tile.PLAYER_ONE_HEAD\n elif self.id == 2:\n return Tile.PLAYER_TWO_HEAD\n\n\nclass HistoryElement:\n def __init__(self, mmap, player_one_direction, player_two_direction):\n self.map = mmap\n self.player_one_direction = player_one_direction\n self.player_two_direction = player_two_direction\n\n\n\n\nclass Game:\n def __init__(self, width, height, pps,mode=None,slide_pram=None):\n\n self.width = width\n self.height = height\n mmap = Map(width, height, Tile.EMPTY, Tile.WALL)\n self.history = [HistoryElement(mmap, None, None)]\n self.pps = pps\n self.winner = None\n # self.loser_len=0\n # self.winner_len = 0\n self.next_p1 = []\n self.next_p2 = []\n self.weight=[random.randint(40,101),random.randint(40,101)]\n # self.reward = 0\n self.done = False\n self.mode=mode\n self.degree=random.randint(-30,30)\n self.slide= slide if slide_pram is None else slide_pram\n\n for pp in self.pps:\n self.history[-1].map[pp.position[0], pp.position[1]] = pp.head()\n\n def map(self):\n return self.history[-1].map.clone()\n\n def get_rate(self,player_num=None):\n\n # return ((self.degree-30)/100) ** 2\n if player_num is None:\n return -((self.degree-30)*0.6)/100\n else:\n return (-((self.degree - 30) * 0.6) / 100)-((70-self.get_weight(player_num))/100)\n\n\n def get_degree(self):\n\n\n return float(self.degree)\n\n def get_degree_silde(self):\n\n return float((-self.slide*100)*(10/6)+30)\n\n def change_degree(self):\n\n if random.random()>0.5:\n temp=self.degree+random.randint(0,3)\n self.degree=min(30,temp)\n\n else:\n temp=self.degree-random.randint(1,5)\n self.degree=max(-30,temp)\n\n def prob_map(self):\n\n temp = np.zeros((MAP_WIDTH + 2, MAP_HEIGHT + 2))\n\n for i in range(MAP_HEIGHT + 2):\n for j in range(MAP_WIDTH + 2):\n temp[i][j] = self.get_degree_silde()\n # print(temp)\n return temp\n def get_weight(self,player_num):\n\n return self.weight[player_num]\n\n def get_multy(self,player_num):\n\n return [self.get_degree(),self.get_weight(player_num)]\n def degree_map(self):\n\n temp = np.zeros((MAP_WIDTH + 2, MAP_HEIGHT + 2))\n\n for i in range(MAP_HEIGHT + 2):\n for j in range(MAP_WIDTH + 2):\n temp[i][j] = self.get_degree()\n return temp\n\n def next_frame(self, action_p1, action_p2, window=None):\n\n map_clone = self.map()\n\n action = [action_p1, action_p2]\n\n for pp in self.pps:\n map_clone[pp.position[0], pp.position[1]] = pp.body()\n\n for id, pp in enumerate(self.pps):\n\n if type(pp.player) == type(ACPlayer()):\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position, action[id])\n\n if self.mode == \"ice\" or self.mode ==\"temper\":\n if pp.position[0] >= 0 and pp.position[1] >= 0 and \\\n pp.position[0] < self.width and pp.position[1] < self.height and map_clone[pp.position[0], pp.position[1]] is Tile.EMPTY:\n\n rate = self.slide if self.mode ==\"ice\" else self.get_rate(id)\n\n if random.random() <= rate:\n\n if(id==0):\n self.history[-1].player_one_direction = self.pps[0].player.direction\n else:\n self.history[-1].player_two_direction = self.pps[1].player.direction\n\n # print(\"미끌\")\n map_clone[pp.position[0], pp.position[1]] = pp.slide()\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position, action[id])\n\n else:\n\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position, id + 1,self.map())\n\n if self.mode==\"ice\" or self.mode ==\"temper\":\n if pp.position[0] >= 0 and pp.position[1] >= 0 and \\\n pp.position[0] < self.width and pp.position[1] < self.height and map_clone[pp.position[0], pp.position[1]] is Tile.EMPTY:\n rate = self.slide if self.mode == \"ice\" else self.get_rate(id)\n\n if random.random() <= rate:\n\n if (id == 0):\n self.history[-1].player_one_direction = self.pps[0].player.direction\n else:\n self.history[-1].player_two_direction = self.pps[1].player.direction\n\n # print(\"미끌\")\n map_clone[pp.position[0], pp.position[1]] = pp.slide()\n (pp.position, pp.player.direction) = pp.player.next_position_and_direction(pp.position,id + 1,self.map(),pp.player.direction)\n\n self.history[-1].player_one_direction = self.pps[0].player.direction\n self.history[-1].player_two_direction = self.pps[1].player.direction\n\n # self.change_degree()\n\n for (id, pp) in enumerate(self.pps):\n if pp.position[0] < 0 or pp.position[1] < 0 or \\\n pp.position[0] >= self.width or pp.position[1] >= self.height:\n pp.alive, done = False, True\n map_clone[pp.position[0], pp.position[1]] = pp.head()\n elif map_clone[pp.position[0], pp.position[1]] is not Tile.EMPTY:\n pp.alive, done = False, True\n map_clone[pp.position[0], pp.position[1]] = pp.head()\n else:\n map_clone[pp.position[0], pp.position[1]] = pp.head()\n \"\"\"\n if not done and independent condition \n get player's longest path\n \n # if not done and self.check_separated(map_clone, self.pps[0]):\n # winner = self.get_longest_path(map_clone, self.pps[0], self.pps[1])\n # if winner == 1:\n # self.pps[1].alive = False\n # elif winner == 2:\n # self.pps[0].alive = False\n # else:\n # self.pps[0].alive = False\n # self.pps[1].alive = False\n \"\"\"\n\n self.history.append(HistoryElement(map_clone, None, None))\n self.next_p1 = self.history[-1].map.state_for_player(1)\n self.next_p2 = self.history[-1].map.state_for_player(2)\n\n if window:\n import pygame\n while True:\n event = pygame.event.poll()\n\n if event.type == pygame.NOEVENT:\n break\n\n for pp in self.pps:\n try:\n pp.player.manage_event(event)\n except:\n if id == 0:\n self.winner = 2\n elif id == 1:\n self.winner = 1\n return False\n\n return True\n\n def step(self, action_p1, action_p2):\n\n alive_count = 0\n alive = None\n\n\n if not self.next_frame(action_p1, action_p2):\n self.done = True\n\n return self.next_p1, self.next_p2, self.done\n for pp in self.pps:\n if pp.alive:\n alive_count += 1\n alive = pp.id\n\n if alive_count <= 1:\n if alive_count == 1:\n if self.pps[0].position[0] != self.pps[1].position[0] or \\\n self.pps[0].position[1] != self.pps[1].position[1]:\n self.winner = alive\n\n self.done = True\n\n return self.next_p1, self.next_p2, self.done\n\n def main_loop(self,model, pop=None,window=None,model2=None):\n\n if window:\n window.render_map(self.map())\n\n if (not model2):\n model2=model\n\n while True:\n alive_count = 0\n alive = None\n\n if window:\n sleep(0.3)\n\n map=self.map()\n with torch.no_grad():\n if type(model) ==maptype:\n action1 = model.act(torch.cat([torch.tensor(pop(map.state_for_player(1))),torch.tensor(self.prob_map()).unsqueeze(0)],0).unsqueeze(0).float())\n else:\n action1 = model.act(torch.tensor(pop(map.state_for_player(1))).unsqueeze(0).float(),torch.tensor([self.get_multy(0)]).to(device))\n\n if type(model2) == maptype:\n action1 = model2.act(torch.cat([torch.tensor(pop(map.state_for_player(2))), torch.tensor(self.prob_map()).unsqueeze(0)],0).unsqueeze(0).float())\n else:\n action2 = model2.act(torch.tensor(pop(map.state_for_player(2))).unsqueeze(0).float(),torch.tensor([self.get_rate()]).to(device))\n\n # action2 = model2.act(torch.tensor(pop(map.state_for_player(2))).unsqueeze(0).float(),torch.tensor([self.slide]).to(device))\n\n # action1 = model.act(torch.tensor(np.expand_dims(np.concatenate((pop(map.state_for_player(1)),np.expand_dims(np.array(self.prob_map()),axis=0)),axis=0), axis=0)).float())\n # action2 = model2.act(torch.tensor(np.expand_dims(np.concatenate((pop(map.state_for_player(2)), np.expand_dims(np.array(self.prob_map()),axis=0)), axis=0),axis=0)).float())\n\n\n if not self.next_frame(action1,action2,window):\n break\n\n for pp in self.pps:\n if pp.alive:\n alive_count += 1\n alive = pp.id\n\n if alive_count <= 1:\n if alive_count == 1:\n if self.pps[0].position[0] != self.pps[1].position[0] or \\\n self.pps[0].position[1] != self.pps[1].position[1]:\n self.winner = alive\n break\n\n if window:\n window.render_map(self.map())\n","sub_path":"Deep-Q-learning_TRON/tron/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":11164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"290461762","text":"#!/usr/bin/env python\n\n\"\"\" A TLS server that spits out random md5 hashes every half second. \"\"\"\n\nimport os\nimport ssl\nfrom hashlib import md5\nimport logging\n\nfrom tornado.ioloop import IOLoop, PeriodicCallback\nfrom tornado.tcpserver import TCPServer\nfrom tornado import options\n\n\nlog = logging.getLogger(__name__)\nport = 4443\nssl_options = {\n 'ssl_version': ssl.PROTOCOL_TLSv1,\n 'certfile': os.path.join(os.path.dirname(__file__), 'server.crt'),\n 'keyfile': os.path.join(os.path.dirname(__file__), 'server.key')\n}\n\n\nclass RandomServer(TCPServer):\n def handle_stream(self, stream, address):\n SpitRandomStuff(stream, address)\n\n\nclass SpitRandomStuff(object):\n def __init__(self, stream, address):\n log.info('Received connection from %s', address)\n self.address = address\n self.stream = stream\n self.stream.set_close_callback(self._on_close)\n self.writer = PeriodicCallback(self._random_stuff, 500)\n self.writer.start()\n\n def _on_close(self):\n log.info('Closed connection from %s', self.address)\n self.writer.stop()\n\n def _random_stuff(self):\n output = os.urandom(60)\n self.stream.write(md5(output).hexdigest() + \"\\n\")\n\n\nif __name__ == '__main__':\n options.parse_command_line()\n server = RandomServer(ssl_options=ssl_options)\n server.listen(port)\n log.info('Listening on port %d...', port)\n # To test from command-line:\n # $ openssl s_client -connect localhost:\n IOLoop.instance().start()\n","sub_path":"SocketServer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"17507912","text":"import pygame\nimport random\n\n\n\nclass game:\n def __init__(self,xmax,ymax):\n\n self.xmax = xmax\n self.ymax = ymax\n\n self._runing = True\n self.screen = None\n self.keyinput = None\n\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n self.y = [100]\n self.x = [100]\n self.direction = 0\n self.fitness = 0\n self.speed = 30\n self.size = 30\n self.aiin = []\n self.aiout = []\n self.movesremaining = 100000\n self.tempdirection1 = None\n self.tempdirection2 = None\n self.paused = False\n\n def on_init(self):\n pygame.init()\n\n self.screen = pygame.display.set_mode((self.xmax, self.ymax))\n self._runing = True\n self.clock = pygame.time.Clock()\n\n def reset(self, draw_game):\n self._runing = True\n self.screen = None\n self.keyinput = None\n\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n self.y = [100]\n self.x = [100]\n self.direction = 0\n self.fitness = 0\n self.speed = 30\n self.size = 30\n self.aiin = []\n self.aiout = []\n self.movesremaining = 100000\n self.tempdirection1 = None\n self.tempdirection2 = None\n\n if draw_game == True:\n self.on_init()\n\n def event(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_q:\n self._runing = False\n\n if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.paused == False:\n self.paused = True\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.paused == True:\n self.paused = False\n\n def get_point(self):\n self.movesremaining += 200\n self.fitness += 20000\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n self.x.append(self.x[-1])\n self.y.append(self.y[-1])\n\n def render_game(self,fps):\n self.screen.fill((0,0,0))\n\n pygame.draw.rect(self.screen, (0, 25, 120), pygame.Rect(self.xobj, self.yobj, self.size, self.size))\n\n for i in range(len(self.x)):\n pygame.draw.rect(self.screen, (255,255,255), pygame.Rect(self.x[i], self.y[i], self.size, self.size))\n\n self.clock.tick(fps)\n pygame.display.flip()\n\n def play_game(self,fps):\n\n\n while self._runing == True:\n\n # gets the user input and changes the direction\n self.keyinput = pygame.key.get_pressed()\n if self.keyinput[pygame.K_w]: self.direction = 1\n elif self.keyinput[pygame.K_s]: self.direction = 0\n elif self.keyinput[pygame.K_d]: self.direction = 2\n elif self.keyinput[pygame.K_a]: self.direction =3\n\n # making other cubes move\n for i in reversed(range(len(self.x))):\n if i != 0:\n self.x[i] = self.x[int(i-1)]\n self.y[i] = self.y[int(i-1)]\n\n # moving the first cube\n if self.direction == 0: self.y[0] += self.speed\n elif self.direction == 1: self.y[0] -= self.speed\n elif self.direction == 2: self.x[0] += self.speed\n elif self.direction == 3: self.x[0] -= self.speed\n\n # pasing to the other side x\n if self.x[0] > self.xmax: self.x[0] = 1\n elif self.x[0] < 0: self.x[0] = self.xmax - 1\n\n # pasing to the other side y\n if self.y[0] > self.ymax: self.y[0] = 1\n elif self.y[0] < 0: self.y[0] = self.ymax -1\n\n if self.x[0] > self.xobj - self.size and self.x[0] < self.xobj + self.size and self.y[0] > self.yobj - self.size and self.y[0] < self.yobj + self.size:\n self.get_point()\n else:\n for i in reversed(range(len(self.x))):\n if i != 0:\n if self.x[0] == self.x[i] and self.y[0] == self.y[i]:\n #print('die')\n self._runing = False\n self.fitness -= 20000\n\n self.event()\n self.render_game(fps)\n\n pygame.quit()\n\n def ai_game(self, ai, draw_game, fps, seeds):\n\n if seeds != None:\n random.seed(seeds)\n self.xobj = random.randint(0,self.xmax - 10)\n self.yobj = random.randint(0,self.ymax - 10)\n\n while self._runing == True:\n\n while self.paused == True:\n self.render_game(fps)\n self.event()\n\n self.aiin.append(self.xobj)\n self.aiin.append(self.yobj)\n\n for i in range(len(self.x)):\n self.aiin.append(self.x[i])\n self.aiin.append(self.y[i])\n\n self.aiout = ai.evaluate(self.aiin)\n self.aiin = []\n\n self.tempdirection2 = self.tempdirection1\n self.tempdirection1 = self.direction\n\n while True:\n if self.aiout[0] == max(self.aiout): self.direction = 0 #s\n elif self.aiout[1] == max(self.aiout): self.direction = 1 #w\n elif self.aiout[2] == max(self.aiout): self.direction = 2 #d\n elif self.aiout[3] == max(self.aiout): self.direction =3 #a\n\n if (self.direction == 0 and 1 == self.tempdirection1) or (self.direction == 1 and 0 == self.tempdirection1) or (self.direction == 2 and 3 == self.tempdirection1) or (self.direction == 3 and 2 == self.tempdirection1):\n self.aiout[self.direction] -= 10000\n else:\n break\n\n if self.tempdirection1 == self.direction:\n self.movesremaining -= 150\n elif self.tempdirection2 == self.direction:\n self.movesremaining -= 150\n\n # making other cubes move\n for i in reversed(range(len(self.x))):\n if i != 0:\n self.x[i] = self.x[int(i-1)]\n self.y[i] = self.y[int(i-1)]\n\n # moving the first cube\n if self.direction == 0: self.y[0] += self.speed\n elif self.direction == 1: self.y[0] -= self.speed\n elif self.direction == 2: self.x[0] += self.speed\n elif self.direction == 3: self.x[0] -= self.speed\n\n # pasing to the other side x\n if self.x[0] > self.xmax: self.x[0] = 1\n elif self.x[0] < 0: self.x[0] = self.xmax - 1\n\n # pasing to the other side y\n if self.y[0] > self.ymax: self.y[0] = 1\n elif self.y[0] < 0: self.y[0] = self.ymax -1\n\n #not dieing\n if self.x[0] > self.xobj - self.size and self.x[0] < self.xobj + self.size and self.y[0] > self.yobj - self.size and self.y[0] < self.yobj + self.size:\n self.get_point()\n else:\n for i in reversed(range(len(self.x))):\n if i != 0:\n if self.x[0] == self.x[i] and self.y[0] == self.y[i]:\n #print('die')\n self._runing = False\n if self.movesremaining < 0:\n self._runing = False\n\n self.movesremaining -= 1\n #print(self.movesremaining)\n\n # fitness\n if self.x[0] > self.xobj:\n if self.y[0] > self.yobj:\n self.fitness -= (self.x[0] - self.xobj) + (self.y[0] - self.yobj)\n elif self.y[0] < self.yobj:\n self.fitness -= (self.x[0] - self.xobj) + (self.yobj - self.y[0])\n elif self.x[0] < self.xobj:\n if self.y[0] > self.yobj:\n self.fitness -= (self.xobj - self.x[0]) + (self.y[0] - self.yobj)\n elif self.y[0] < self.yobj:\n self.fitness -= (self.xobj - self.x[0]) + (self.yobj - self.y[0])\n\n #if ( self.x[0] - self.xobj < 100 or self.x[0] - self.xobj < -100 ) and ( self.y[0] - self.yobj < 100 or self.y[0] - self.yobj < -100 ):\n #self.fitness += 1\n\n # options to draw the game\n if draw_game == True:\n self.render_game(fps)\n self.event()\n\n pygame.quit()\n return self.fitness\n\n\n\nif __name__ == \"__main__\" :\n App = game(700,700)\n App.on_init()\n App.play_game(15)\n\n\n'''\n\n\nwhile not done:\n screen.fill((0,0,0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_q:\n done = True\n\n # gets the user input and changes the direction\n keyinput = pygame.key.get_pressed()\n if keyinput[pygame.K_w]: direction = 1\n elif keyinput[pygame.K_s]: direction = 0\n elif keyinput[pygame.K_d]: direction = 2\n elif keyinput[pygame.K_a]: direction =3\n\n # changes the direction of the verlocety\n if direction == 0: y += 5\n elif direction == 1: y -= 5\n elif direction == 2: x += 5\n elif direction == 3: x -= 5\n\n # pasing to the other side x\n if x > xmax: x = 1\n elif x < 0: x = xmax - 1\n\n # pasing to the other side y\n if y > ymax: y = 1\n elif y < 0: y = ymax -1\n\n pygame.draw.rect(screen, (0, 25, 120), pygame.Rect(xobj, yobj, 30, 30))\n pygame.draw.rect(screen, colour, pygame.Rect(x, y, 30, 30))\n\n clock.tick(60)\n pygame.display.flip()\n\n\nsnake\n\n'''\n","sub_path":"snake/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":10206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"621703324","text":"\"\"\" Simple FancyLED example for NeoPixel strip\n\"\"\"\n\nimport board\nimport neopixel\nimport adafruit_fancyled as fancy\n\n# Function names are kept the same as FastLED examples, which normally\n# upsets pylint. Disable name-checking so this passes muster.\n# pylint: disable=invalid-name\n\nNUM_LEDS = 23\n\n# A dynamic gradient palette is a compact representation of a color palette\n# that lists only the key points (specific positions and colors), which are\n# later interpolated to produce a full 'normal' color palette.\n# This one is an RGB spectrum -- red to yellow, green, blue, ... back to red.\nRAINBOW = bytes([\n 0, 255, 0, 0,\n 32, 171, 85, 0,\n 64, 171, 171, 0,\n 96, 0, 255, 0,\n 128, 0, 171, 85,\n 160, 0, 0, 255,\n 192, 85, 0, 171,\n 224, 171, 0, 85,\n 255, 255, 0, 0])\n\n# Here the gradient palette is converted to a full normal palette.\n# First we need a list to hold the resulting palette...it can be\n# filled with nonsense but the list length needs to match the desired\n# palette length (in FastLED, after which FancyLED is modeled, color\n# palettes always have 16, 32 or 256 entries...we can actually use whatever\n# length we want in CircuitPython, but for the sake of consistency, let's\n# make it a 256-element palette...\nPALETTE = [0] * 256\nfancy.loadDynamicGradientPalette(RAINBOW, PALETTE)\n\n# The dynamic gradient step is optional...some projects will just specify\n# a whole color palette directly on their own, not expand it from bytes.\n\n# Declare a NeoPixel object on pin D6 with NUM_LEDS pixels, no auto-write\nPIXELS = neopixel.NeoPixel(board.D6, NUM_LEDS, brightness=1.0,\n auto_write=False)\n\ndef FillLEDsFromPaletteColors(palette, offset):\n \"\"\" This function fills the global PIXELS NeoPixel strip from a color\n palette plus an offset to allow us to 'spin' the colors. In FancyLED\n (a la FastLED), palette indices are multiples of 16 (e.g. first palette\n entry is index 0, second is index 16, third is 32, etc) and indices\n between these values will interpolate color between the two nearest\n palette entries.\n \"\"\"\n\n for i in range(NUM_LEDS):\n # This looks up the color in the palette, scaling from\n # 'palette space' to 'pixel space':\n color = fancy.ColorFromPalette(\n palette, int(i * len(palette) * 16 / NUM_LEDS + offset),\n 255, True)\n # Gamma correction gives more sensible-looking colors\n PIXELS[i] = fancy.applyGamma_video(color)\n\n# This is an offset (0-4095) into the color palette to get it to 'spin'\nADJUST = 0\n\nwhile True:\n FillLEDsFromPaletteColors(PALETTE, ADJUST)\n PIXELS.show()\n ADJUST += 50 # Bigger number = faster spin\n if ADJUST >= 4096:\n ADJUST -= 4096\n","sub_path":"examples/neopixel_rotate.py","file_name":"neopixel_rotate.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"2860973","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport numpy.random as rd\r\nimport mpl_toolkits.mplot3d.axes3d as p3\r\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\r\nimport matplotlib.animation as animation\r\n\r\n\r\n\r\n\r\n################################################################\r\n###-----------------Définition des fonctions-----------------### \r\n################################################################ \r\n\r\ndef plot_cube(cube_definition): #La fonction volée\r\n cube_definition_array = [\r\n np.array(list(item))\r\n for item in cube_definition\r\n ]\r\n\r\n points = []\r\n points += cube_definition_array\r\n vectors = [\r\n cube_definition_array[1] - cube_definition_array[0],\r\n cube_definition_array[2] - cube_definition_array[0],\r\n cube_definition_array[3] - cube_definition_array[0]\r\n ]\r\n\r\n points += [cube_definition_array[0] + vectors[0] + vectors[1]]\r\n points += [cube_definition_array[0] + vectors[0] + vectors[2]]\r\n points += [cube_definition_array[0] + vectors[1] + vectors[2]]\r\n points += [cube_definition_array[0] + vectors[0] + vectors[1] + vectors[2]]\r\n\r\n points = np.array(points)\r\n\r\n edges = [\r\n [points[0], points[3], points[5], points[1]],\r\n [points[1], points[5], points[7], points[4]],\r\n [points[4], points[2], points[6], points[7]],\r\n [points[2], points[6], points[3], points[0]],\r\n [points[0], points[2], points[4], points[1]],\r\n [points[3], points[6], points[7], points[5]]\r\n ]\r\n\r\n\r\n faces = Poly3DCollection(edges, linewidths=1, edgecolors='k')\r\n faces.set_facecolor((0,0,1,0.1))\r\n\r\n axes.add_collection3d(faces)\r\n\r\n\r\n\r\n\r\ndef norme(Vec3D):\r\n return np.sqrt(normeCarree(Vec3D))\r\n\r\ndef normeCarree(Vec3D):\r\n return Vec3D[0]**2+Vec3D[1]**2+Vec3D[2]**2\r\n\r\n#Avec la vitesse/température T et l'écart type E, la fonction renvoie UNE vitesse prise dans une gaussienne\r\ndef GenVitesse(T,E):\r\n vit_xyz=np.zeros(3)\r\n for i in range(3):\r\n vit_xyz[i]=rd.random()\r\n NormEtVit=norme(vit_xyz)/rd.normal(T,E) #constante permettant de normer vit_xyz pour ensuite lui donner une norme prise au hasard dans une gaussienne\r\n\r\n for i in range(3):\r\n signe=rd.random()\r\n if signe<0.5:\r\n vit_xyz[i]=vit_xyz[i]/NormEtVit\r\n else:\r\n vit_xyz[i]=-vit_xyz[i]/NormEtVit\r\n \r\n return np.array(vit_xyz)\r\n\r\n#La fonction renvoie la distribution des corps selon la demi-longueur envoyée\r\ndef GenPosition(nombrePlanete,rayon,methode):\r\n if methode==\"Cube\":\r\n Ecart=(2*rayon)/((nombrePlanete)**(1/3))\r\n T=[]\r\n for i in np.arange(-rayon,rayon,Ecart):\r\n for j in np.arange(-rayon+Ecart/2,rayon,Ecart):\r\n for z in np.arange(-rayon,rayon,Ecart):\r\n T.append([i,j,z])\r\n if len(T)r:\r\n return \"x+\"\r\n if TPosy[i,planete]<-r:\r\n return \"y-\"\r\n if TPosy[i,planete]>r:\r\n return \"y+\"\r\n if TPosz[i,planete]<-r:\r\n return \"z-\"\r\n if TPosz[i,planete]>r:\r\n return \"z+\"\r\n return(\"no\")\r\n\r\n#Modifie, selon le resultat de la fonction DansBoite(), la vitesse et la position de la particule à l'étape i pour simuler une collision, enregistre aussi la quantité de mouvement transmise aux parois\r\ndef modif(info):\r\n if info==\"no\":\r\n return()\r\n if info=='x-':\r\n TPosx[i,planete]=TPosx[i,planete] + 2*(-TailleBoite-TPosx[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitx[i,planete])\r\n TVitx[i,planete]=-TVitx[i,planete]\r\n return()\r\n if info=='x+':\r\n TPosx[i,planete]=TPosx[i,planete] + 2*(TailleBoite-TPosx[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitx[i,planete])\r\n TVitx[i,planete]=-TVitx[i,planete]\r\n return()\r\n if info=='y-':\r\n TPosy[i,planete]=TPosy[i,planete] + 2*(-TailleBoite-TPosy[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVity[i,planete])\r\n TVity[i,planete]=-TVity[i,planete]\r\n return()\r\n if info=='y+':\r\n TPosy[i,planete]=TPosy[i,planete] + 2*(TailleBoite-TPosy[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVity[i,planete])\r\n TVity[i,planete]=-TVity[i,planete]\r\n return()\r\n if info=='z-':\r\n TPosz[i,planete]=TPosz[i,planete] + 2*(-TailleBoite-TPosz[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitz[i,planete])\r\n TVitz[i,planete]=-TVitz[i,planete]\r\n return()\r\n if info=='z+':\r\n TPosz[i,planete]=TPosz[i,planete] + 2*(TailleBoite-TPosz[i,planete])\r\n Moment[i]=Moment[i]+abs(2*TVitz[i,planete])\r\n TVitz[i,planete]=-TVitz[i,planete]\r\n \r\n\r\ndef distance(x1,x2,y1,y2,z1,z2):\r\n\treturn np.sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)\r\n\r\ndef Ecinetique(vx,vy,vz):\r\n\treturn 0.5*1*(vx**2+vy**2+vz**2)\r\n\r\ndef Epotentielle(d):\r\n\treturn 0.5*((1/d**12)-(1/d**6)) #Multiplication par 0.5 parceque je compte deux fois l'energie: pour un couple {i,j} de particule, je compte Eij et Eji, donc il faut diviser par deux\r\n\r\n\r\n\r\n#####################################################################\r\n###-----------------Initialisation des paramètres-----------------### \r\n##################################################################### \r\nrd.seed(1)\r\n\r\n#Nombre de corps\r\nnombrePlan=15\r\n\r\n#Durée de la simulation\r\ntemps=30\r\n\r\n#Intervalle de temps (Il vaut mieux garder un multiple de 10 sinon, le ttab peut avoir des problemes de dimensionnement (N+1 colonnes plutot que N))\r\ndt=0.01\r\n\r\n#Nombre de simulation(s)\r\nN=int(temps/dt)\r\n\r\n\r\n#Définition des tableaux contenant les différentes données\r\nttab=np.arange(dt,temps,dt)\r\n\r\n#Position et vitesse\r\nTPosx=np.zeros((N,nombrePlan))\r\nTPosy=np.zeros((N,nombrePlan))\r\nTPosz=np.zeros((N,nombrePlan))\r\nTVitx=np.zeros((N,nombrePlan))\r\nTVity=np.zeros((N,nombrePlan))\r\nTVitz=np.zeros((N,nombrePlan))\r\n\r\n#Energie et quantité de mouvement\r\nEpot=np.zeros(N)\r\nEcin=np.zeros(N)\r\nMoment=np.zeros(N) #Quantité de mouvement transmise aux parois, en valeur absolue puisqu'elle ne sert qu'à trouver une pression\r\n\r\n#Demi longueur du cube dans lequel on place les corps et leurs vitesses + ecart type de la gaussienne en t=0\r\nTailleInitiale=1.5\r\nVitesseInitiale=0.001\r\nEcartType=0.00\r\n\r\n#Taille de la boite dans laquelle se passe les collisions (à garder STRICTEMENT inférieur à: TailleInitiale)\r\nTailleBoite=10\r\n\r\ncube_definition = [\r\n (-TailleBoite,-TailleBoite,-TailleBoite), (TailleBoite,-TailleBoite,-TailleBoite), (-TailleBoite,TailleBoite,-TailleBoite), (-TailleBoite,-TailleBoite,TailleBoite)\r\n]\r\n\r\n#Generation des conditions initiales\r\nAttributionInitiale(TailleInitiale,VitesseInitiale,EcartType)\r\n\r\nTVitx[0,0]=5\r\nTVity[0,0]=-5\r\nTVitz[0,0]=5\r\nTPosx[0,0]=9.98\r\nTPosy[0,0]=9.98\r\nTPosz[0,0]=9.98\r\n\r\n############################################################\r\n###-----------------Programme Principale-----------------### \r\n############################################################ \r\n\r\n\r\nprint(\"Début des calculs\")\r\nfor i in range(1,N):\r\n print(i,\"/\",N)\r\n for planete in range(nombrePlan):\r\n ax=0\r\n ay=0\r\n az=0\r\n for planeteAutre in range(nombrePlan):\r\n if planeteAutre!=planete: \r\n a=CalculAcceleration()\r\n ax+=a[0]\r\n ay+=a[1]\r\n az+=a[2]\r\n Epot[i-1]=Epot[i-1]+Epotentielle(a[3])\r\n CalculVitesseEtPosition()\r\n modif(DansBoite(TailleBoite)) #A mettre en commentaire pour desactiver les collisions\r\n Ecin[i]=Ecin[i]+Ecinetique(TVitx[i,planete],TVity[i,planete],TVitz[i,planete]) \r\n \r\n \r\n###############################################\r\n###-----------------Calculs-----------------### \r\n###############################################\r\n\r\n#Calcul de la pression exercée sur les parois \r\naireBoite=6*(2*TailleBoite)**2\r\npas=100\r\nnombreDivision=int(N/pas)\r\n\r\nttab2=np.linspace(0,dt*N,nombreDivision)\r\nTMoment=np.zeros(nombreDivision)\r\nfor i in range(nombreDivision):\r\n TMoment[i]=sum(Moment[i*pas:(i*pas)+pas])\r\nTpress=TMoment/(pas*dt*aireBoite)\r\n\r\n#Calcul temperature\r\nkb=1\r\n\r\neneCinMoyenne=0\r\nfor i in range(int(N/2),N):\r\n eneCinMoyenne+=2*Ecin[i]/N\r\ntemperature=eneCinMoyenne/(1.5*kb*nombrePlan)\r\n\r\n\r\n\r\n#Pression exercée en moyenne sur les parois pendant le temps (dt*N)/2\r\npression=sum(Tpress[:int(len(Tpress)/2)])*2/len(Tpress)\r\n\r\n#Calcul de l'énergie totale \r\nEtot=Epot[1:-1]+Ecin[1:-1]\r\n\r\nprint(\"pression=\", pression,\"temperature=\",temperature ) \r\n\r\n\r\n \r\n###########################################################\r\n###-----------------Affichage Graphique-----------------### \r\n########################################################### \r\n \r\nfig = plt.figure()\r\naxes = p3.Axes3D(fig)\r\ndef animate(i):\r\n i=i*10\r\n axes.clear()\r\n axes.plot(TPosx[i,:1],TPosy[i,:1],TPosz[i,:1],\"ro\")\r\n axes.plot(TPosx[i,1:],TPosy[i,1:],TPosz[i,1:],\"bo\")\r\n plot_cube(cube_definition)\r\n axes.set_xlim3d([-TailleBoite, TailleBoite])\r\n\r\n axes.set_ylim3d([-TailleBoite, TailleBoite])\r\n\r\n axes.set_zlim3d([-TailleBoite, TailleBoite])\r\n\r\n \r\nani = animation.FuncAnimation(fig, animate, interval=10)\r\n#ani.save('./gif/animation.gif', writer='imagemagick', fps=10)\r\n\r\n \r\n\r\n\"\"\" \r\nplt.legend()\r\nplt.figure()\r\nplt.plot(ttab[:-1],Epot[1:-1],label=\"Epot\")\r\nplt.plot(ttab[:-1],Ecin[1:-1],label=\"Ecin\")\r\nplt.plot(ttab[:-1],Etot,label=\"Etot\")\r\n\r\nplt.figure()\r\nplt.plot(ttab2,Tpress,label='Pression')\r\nplt.figure()\r\nplt.plot(ttab[:-1],Moment[1:-1],label=\"Quantité de mouvement\")\r\n\r\nplt.legend()\r\n\"\"\"\r\nplt.show()","sub_path":"dyna_mole_5.8.py","file_name":"dyna_mole_5.8.py","file_ext":"py","file_size_in_byte":11578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"137194542","text":"'''\n@Author: Ru_j\n@Date: 2020-03-13 19:50:16\n@LastEditors: Ru_j\n@LastEditTime: 2020-03-13 21:43:15\n@Description:\n'''\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_boston\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import SGDRegressor, Ridge, RidgeCV\nfrom sklearn.decomposition import PCA\nimport pandas as pd\nimport os\nfrom sklearn.cluster import KMeans\n\n\ndef SGD_boston():\n boston = load_boston()\n x = boston.data\n y = boston.target\n train_x, test_x, train_y, test_y = \\\n train_test_split(x, y, test_size=.25)\n std_s = StandardScaler()\n train_x = std_s.fit_transform(train_x)\n test_x = std_s.fit_transform(test_x)\n\n sgd = SGDRegressor()\n sgd.fit(train_x, train_y)\n score = sgd.score(test_x, test_y)\n predict_y = sgd.predict(test_x)\n print(score)\n print(predict_y[:20])\n print(test_y[:20])\n # print(sgd.coef_)\n # print(sgd.intercept_)\n\n return None\n\n\ndef ridge_boston():\n boston = load_boston()\n x = boston.data\n y = boston.target\n train_x, test_x, train_y, test_y = \\\n train_test_split(x, y, test_size=.25)\n std_s = StandardScaler()\n train_x = std_s.fit_transform(train_x)\n test_x = std_s.fit_transform(test_x)\n\n # ridge = Ridge(alpha=1.5)\n ridge = RidgeCV(alphas=[1e-3, 1e-2, 1e-1, 1], cv=4)\n ridge.fit(train_x, train_y)\n score = ridge.score(test_x, test_y)\n predict_y = ridge.predict(test_x)\n print(score)\n print(predict_y[:20])\n print(test_y[:20])\n return None\n\n\ndef pca_kmeans():\n path = os.path.dirname(__file__) + \\\n '/machine_learning_data/'\n products = pd.read_csv(path + 'products.csv')\n orders = pd.read_csv(path + 'orders.csv')\n aisles = pd.read_csv(path + 'aisles.csv')\n prior = pd.read_csv(path + 'order_products_prior.csv', iterator=True)\n prior = prior.get_chunk(10000)\n table_1 = pd.merge(prior, products, on=['product_id', 'product_id'])\n table_2 = pd.merge(table_1, orders, on=['order_id', 'order_id'])\n table = pd.merge(table_2, aisles, on=['aisle_id', 'aisle_id'])\n\n data = pd.crosstab(table['user_id'], table['aisle'])\n _pca = PCA(n_components=0.95)\n data = _pca.fit_transform(data)\n\n km = KMeans()\n km.fit(data)\n predict = km.predict(data)\n print(predict[:100])\n\n return None\n\n\nif __name__ == \"__main__\":\n SGD_boston()\n ridge_boston()\n pca_kmeans()\n","sub_path":"python/day10/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"346286904","text":"#io_utilities.py\n#open es como si fuera una clase\nfilepath = './data/iris.data' #r de read\n\nwith open (filepath ,'r') as fp:\n data = fp.read()\n\ndata_lines = data.split('\\n')\ndata_final = [f.split(',')for f in data_lines]\n\nprint (data_final)\n","sub_path":"io_utilities.py","file_name":"io_utilities.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"8099633","text":"from selenium import webdriver\r\nfrom PyQt5 import QtWidgets\r\nfrom PyQt5 import QtCore\r\nfrom PyQt5.QtWidgets import QToolButton, QSizePolicy, QLabel, QLineEdit,QPushButton\r\nimport random\r\nimport keyboard\r\nimport re\r\n# options=webdriver.ChromeOptions()\r\n# options.add_argument('headless')#창을 안띄우는 headless모드\r\n# options.add_argument('window-size=1920x1080')\r\n# options.add_argument(\"disable-gpu\")#gpu가속 끔\r\n# #user-agent값을 변경하여 headless모드 감지를 방지\r\n# options.add_argument(\"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\")\r\n# options.add_argument(\"lang=ko_KR\") #headless모드에선 언어설정이 안되있으므로 한국어로 설정(감지 방지)\r\ndriver = webdriver.Chrome('C://Users//dhrms//Downloads//chromedriver_win32\\\\chromedriver.exe')#,chrome_options=options)\r\n\r\nclass start(QtWidgets.QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.layout=QtWidgets.QHBoxLayout(self)\r\n\r\n self.id_layout = QtWidgets.QVBoxLayout(self)\r\n self.pwd_layout = QtWidgets.QVBoxLayout(self) #QV=가로 QH=세로\r\n\r\n self.id=QLabel(\"ID\")\r\n self._id=QLineEdit()\r\n self.pwd=QLabel(\"password\")\r\n self._pwd=QLineEdit()\r\n\r\n self.id_layout.addWidget(self.id)\r\n self.id_layout.addWidget(self._id)\r\n\r\n self.pwd_layout.addWidget(self.pwd)\r\n self.pwd_layout.addWidget(self._pwd)\r\n self.layout.addLayout(self.id_layout)\r\n self.layout.addLayout(self.pwd_layout)\r\n\r\n self.setLayout(self.layout)\r\n\r\n self._pwd.setEchoMode(QLineEdit.Password)\r\n self._pwd.returnPressed.connect(self.login)\r\n\r\n self.show()\r\n\r\n def login(self):\r\n driver.get(\"https://www.instagram.com/accounts/login/\")\r\n driver.find_element_by_name('username').send_keys(self._id.text())\r\n driver.find_element_by_name('password').send_keys(self._pwd.text())\r\n driver.implicitly_wait(10)\r\n driver.find_elements_by_tag_name('button')[1].click()\r\n driver.implicitly_wait(100)\r\n self.newWindow = Main()\r\n self.newWindow.show()\r\n self.close()\r\n\r\n\r\nclass Main(QtWidgets.QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.layout_m = QtWidgets.QHBoxLayout(self) #전체틀\r\n self.start_layout = QtWidgets.QVBoxLayout() #버튼을 담을 틀\r\n self.setFixedSize(300, 200)\r\n \r\n ''' 수정 필요 '''\r\n \r\n self.target=QLabel(\"상대의 아이디를 입력하세요\")\r\n self._target=QLineEdit()\r\n self.like = self.createButton(\"좋아요\",self.clicklike)#버튼watch\r\n #self.comment = self.createButton(\"댓글\",self.clickcomment)#버튼graph\r\n \r\n self.like.resize(self.like.sizeHint())#sizeHint=holds the recommended size for the widget\r\n #self.comment.resize(self.comment.sizeHint())\r\n\r\n #틀에 버튼 담음\r\n #self.start_layout.addWidget(self.comment)\r\n self.start_layout.addWidget(self.target)\r\n self.start_layout.addWidget(self._target)\r\n self.layout_m.addLayout(self.start_layout)#전체틀에 버튼을 담은 틀을 담음\r\n self.layout_m.addWidget(self.like)\r\n self.setLayout(self.layout_m)\r\n \r\n self.show()\r\n \r\n self.timer = QtCore.QTimer() # 타이머 생성\r\n \r\n # 함수 연결\r\n self.timer.timeout.connect(self.clicklike) # 타임아웃 이벤트를 showWatch와 연결\r\n # 정한 시간이 지날때마다 show_time 실행\r\n self.timer.start(1000*60*60)#1시간에 한번씩\r\n\r\n\r\n def clicklike(self):\r\n # driver.find_element_by_name('username').send_keys(\"01037395297\")\r\n # driver.find_element_by_name('password').send_keys(\"dh241152!\")\r\n driver.get('https://www.instagram.com/{}'.format(self._target.text()))\r\n # driver.get('https://www.instagram.com/{}/'.format(input_target_id))\r\n #첫번째 게시글 클릭\r\n driver.find_elements_by_css_selector('.v1Nh3.kIKUG._bz0w')[0].find_element_by_tag_name('a').click()\r\n driver.implicitly_wait(10)\r\n #좋아요누르기\r\n driver.get(driver.current_url)\r\n temp1=driver.find_elements_by_class_name('eo2As ')\r\n temp1[0].find_element_by_class_name('wpO6b ').click()\r\n #사진의 정보가져와서 필요한데이터 추출\r\n img_information=driver.find_elements_by_tag_name('img')[1].get_attribute('alt')\r\n img_information=img_information.split(': ')\r\n img_information=img_information[1].split(' and ')\r\n #print(img_information)\r\n food = [\"맛있겠네\",\"맛있어 보이는구나!\",\"다음에 나도 데려가~~\", \"돼지야!\"]\r\n people=[\"오 아주 잘나왔군!\", \"정말 멋쟁이군\", \"우도환 닮았다\", \"손나은 닮았다\"]\r\n\r\n for i in img_information:\r\n if re.search('people',i):\r\n case=\"인물\"\r\n break\r\n if re.search('food',i):\r\n case=\"음식\"\r\n break\r\n else:\r\n case=\"기타\"\r\n\r\n if case==\"인물\":\r\n rand_number=random.randint(0,3)\r\n comment=people[rand_number]\r\n elif case==\"음식\":\r\n rand_number=random.randint(0,3)\r\n comment=food[rand_number]\r\n else:\r\n comment=\"^^7\"\r\n #댓글입력\r\n temp1[0].find_elements_by_class_name('wpO6b ')[1].click()\r\n driver.find_element_by_tag_name('textarea').send_keys(comment)\r\n driver.implicitly_wait(10)\r\n driver.find_element_by_class_name('X7cDz').find_element_by_tag_name('button').click()\r\n \r\n \r\n def createButton(self, text, function):\r\n button = Button(text)\r\n button.clicked.connect(function)\r\n return button\r\n\r\n\r\n\r\nclass Button(QToolButton):\r\n def __init__(self, text):\r\n super().__init__()\r\n buttonStyle = '''\r\n QToolButton:hover {border:1px solid #0078d7; background-color:#e5f1fb;}\r\n QToolButton:pressed {background-color:#a7c8e3}\r\n QToolButton {font-size:11pt; font-family:나눔고딕; border:1px solid #d6d7d8; background-color:#f0f1f1}\r\n '''\r\n self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)\r\n self.setText(text)\r\n self.setStyleSheet(buttonStyle)\r\n\r\n def sizeHint(self):\r\n size = super(Button, self).sizeHint()\r\n size.setHeight(size.height() + 30)\r\n size.setWidth(max(size.width(), size.height()))\r\n return size\r\n\r\nif __name__ == '__main__':\r\n app = QtWidgets.QApplication([])\r\n win=start()\r\n app.exec_()","sub_path":"Like&comment.py","file_name":"Like&comment.py","file_ext":"py","file_size_in_byte":6720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"252429319","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\n\nfrom src.sparse_distributed_representation import SDR\nfrom src.numeric_encoder import NumericEncoder\nfrom src.category_encoder import CategoryEncoder\nfrom src.sam_fabric import SAM\nfrom examples.sam_viz import plot_pors, plot_sam\n\n\nfrom sklearn.datasets import make_moons\n\n\ndef moon_test():\n\n # get moon raw data with 1% noise and 200 samples\n #\n data_set, labels = make_moons(n_samples=200,\n noise=0.01,\n random_state=0)\n\n # create a numeric encoder and label encoder\n #\n numeric_encoder = NumericEncoder(min_step=0.005,\n n_bits=40,\n enc_size=2048,\n seed=123)\n\n label_encoder = CategoryEncoder(n_bits=40,\n enc_size=2048,\n seed=456)\n\n # construct a training set of SDRs encoding the x and y values of the 2D moons and\n # encoding the label\n #\n training_graphs = []\n\n for idx in range(len(data_set)):\n\n # the xy_sdr represents the sparse encoding of a 2D point\n #\n xy_sdr = SDR()\n\n # here enc_key identifies an edge to an x value\n #\n xy_sdr.add_encoding(enc_key=('x',), value=data_set[idx][0], encoder=numeric_encoder)\n\n # here enc_key identifies an edge to a y value\n #\n xy_sdr.add_encoding(enc_key=('y',), value=data_set[idx][1], encoder=numeric_encoder)\n\n # the label_sdr represents the sparse encoding of the label\n #\n label_sdr = SDR()\n label_sdr.add_encoding(enc_key=('label',), value=str(labels[idx]), encoder=label_encoder)\n\n training_graphs.append({'xy': xy_sdr, 'label': label_sdr})\n\n # the xy_sdr and label_sdr will be trained in different regions of the SAM\n # but associated with each other because they occur at the same time\n # The sam_params is a default config for each region of the SAMFabric\n #\n regional_sam_params = {\n # an incoming training sdr must be at least 70% similar to a neuron to be mapped to it\n 'similarity_threshold': 0.7,\n\n # neurons that are at least 63% (0.7 * 0.9) similar to the incoming sdr are considered to be in the same community\n 'community_factor': 0.9,\n\n # the level below which a weight is considered zero and will be deleted\n 'prune_threshold': 0.01,\n\n # a set of enc_type tuples to be used in learning - settin to None implies all enc_types will be learned\n 'activation_enc_keys': None}\n\n association_sam_params = {\n # an incoming training sdr must be at least 50% similar to a neuron to be mapped to it\n 'similarity_threshold': 0.5,\n\n # neurons that are at least 45% (0.5 * 0.9) similar to the incoming sdr are considered to be in the same community\n 'community_factor': 0.9,\n\n # the level below which a weight is considered zero and will be deleted\n 'prune_threshold': 0.01,\n\n # a set of enc_type tuples to be used in learning - setting to None implies all enc_types will be learned\n 'activation_enc_keys': None}\n\n # we have the possibility of having different configurations per region\n #\n region_params = {'xy': regional_sam_params,\n 'label': regional_sam_params}\n\n sam_fabric = SAM(spatial_params=region_params, association_params=association_sam_params)\n\n pors = []\n\n for t_idx in range(len(training_graphs)):\n por = sam_fabric.train(sdrs=training_graphs[t_idx])\n pors.append(por)\n\n sam_dict = sam_fabric.to_dict(decode=True)\n\n plot_sam(sam_region=sam_dict['xy'],\n raw_data=data_set,\n xyz_types=[('x',), ('y',)],\n colour_nodes=None,\n title='Moons')\n\n xy_pors = [por['xy'] for por in pors]\n\n plot_pors(xy_pors)\n\n print('Finished')\n\n\nif __name__ == '__main__':\n\n moon_test()\n","sub_path":"examples/sam_fabric_moon.py","file_name":"sam_fabric_moon.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"624708181","text":"import os\nimport argparse\n\nimport sys\n\nsys.path.append(os.getcwd())\n\nimport torch\n\nprint(\"Current working path:\", os.getcwd())\nmodels = [\"seq2seq\", \"memnn\", \"transformer\", \"itdd\"]\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model\", type=str, default=\"seq2seq\", help=\" or \".join(models))\nparser.add_argument(\n \"--embed_size\", type=int, default=128, help=\"default 64. word embedding size\"\n)\nparser.add_argument(\n \"--batch_size\", type=int, default=32, help=\"default 32. input batch size\"\n)\nparser.add_argument(\n \"--num_epochs\", type=int, default=40, help=\"default 40. the number of epochs\"\n)\n\nparser.add_argument(\n \"--start_epoch\", type=int, default=0, help=\"resume epoch count, default=0\"\n)\nparser.add_argument(\n \"--resume\", type=int, default=1, help=\"defalut 1. read pretrained models\"\n)\nparser.add_argument(\"--seed\", type=int, default=1111, help=\"random seed\")\nargs = parser.parse_args()\n\ntorch.manual_seed(args.seed)\n\n\n# command line parameters\nmodel = args.model\nembed_size = args.embed_size\nbatch_size = args.batch_size\nnum_epochs = args.num_epochs\nstart_epoch = args.start_epoch\nresume = args.resume\n","sub_path":"snow/utils/configer.py","file_name":"configer.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"275117395","text":"# -*- coding: utf-8 -*-\n# Django settings for aikidodze project.\nimport os\n\nDEBUG = False\nTEMPLATE_DEBUG = False\nTHUMBNAIL_DEBUG = False\n\nADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)\n\nSITE_ROOT = os.path.realpath(os.path.dirname(__file__))\nMANAGERS = ADMINS\n\nDATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\nDATABASE_NAME = \"*********\" # Or path to database file if using sqlite3.\nDATABASE_USER = '*********' # Not used with sqlite3.\nDATABASE_PASSWORD = '*********' # Not used with sqlite3.\nDATABASE_HOST = 'localhost' # Set to empty string for localhost. Not used with sqlite3.\nDATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.\n\nDEFAULT_CHARSET = \"utf-8\"\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'Asia/Novosibirsk'\n\ngettext = lambda s: s\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'ru-ru'\n\nLANGUAGES = (\n ('ru', gettext('Russian')),\n)\nCMS_LANGUAGES = (\n ('ru', gettext('Russian')),\n)\nCMS_LANGUAGE_CONF = {\n 'ru':['ru'],\n}\n\nCMS_DEFAULT_LANGUAGE = 'ru'\n\nCMS_FRONTEND_LANGUAGES = (\"ru\",)\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\nURL_ROOT= ''#/sibposad'\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = os.path.join(SITE_ROOT, 'media')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nMEDIA_URL = URL_ROOT+'/media/'\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\nADMIN_MEDIA_PREFIX = URL_ROOT+'/media/amedia/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'fm5s3rn(#f2fkzpzawdk(8j_0j$on@a&lwyq(0ds(5w%1vl!=m'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n # 'django.template.loaders.eggs.load_template_source',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'cms.middleware.media.PlaceholderMediaMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n #'cms.middleware.multilingual.MultilingualURLMiddleware',\n)\n\nROOT_URLCONF = 'sibposad.urls'\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.auth\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.request\",\n \"django.core.context_processors.media\",\n \"cms.context_processors.media\",\n \"main.main_processor.template\",\n)\n\nTEMPLATE_DIRS = (\n os.path.join(SITE_ROOT, 'tmpl'),\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\nCMS_TEMPLATES = (\n ('base.html', gettext('default')),\n ('index.html', gettext('index')),\n ('main.html',gettext('main')),\n ('news.html',gettext('news')),\n ('service.html',gettext('service')),\n ('contacts.html',gettext('contacts')),\n)\n\nCMS_APPLICATIONS_URLS = (\n ('news.urls', 'News'),\n)\n\n#CMS_NAVIGATION_EXTENDERS = (\n# ('cmsplugin_news.navigation.get_nodes', 'News navigation'),\n#)\n\nCMS_SEO_FIELDS = True\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.admin',\n 'django.contrib.sites',\n 'cms',\n 'cms.plugins.text',\n 'cms.plugins.picture',\n 'cms.plugins.link',\n 'cms.plugins.file',\n 'cms.plugins.video',\n 'menus',\n 'mptt',\n 'publisher',\n #'south',\n 'sorl.thumbnail',\n 'news',\n 'gallery',\n 'opinion',\n 'roster',\n)\n\nROSTER_PAGE = 9\n\n\nWYM_TOOLS = \",\\n\".join([\n \"{'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}\",\n \"{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'}\",\n \"{'name': 'Superscript', 'title': 'Superscript', 'css': 'wym_tools_superscript'}\",\n \"{'name': 'Subscript', 'title': 'Subscript', 'css': 'wym_tools_subscript'}\",\n \"{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'}\",\n \"{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'}\",\n \"{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'}\",\n \"{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'}\",\n \"{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'}\",\n \"{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}\",\n \"{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'}\",\n \"{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'}\",\n \"{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'}\",\n])\n\nWYM_CLASSES = \",\\n\".join([\n \"{'name': 'transparent', 'title': 'Таблица без границ', 'expr': 'table'}\",\n])\n\nWYM_STYLES = \",\\n\".join([\n \"{'name': '.transparent', 'css': 'background-color: #E1E8F1'}\",\n])\n","sub_path":"ExampleDjangoCMS/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"243597041","text":"# -*- coding: utf-8 -*-\n\nimport math\nimport random\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\n\ndef get_softmax(z, tau=1.0):\n exp_z = np.exp((z - np.max(z)) / tau)\n p = list(exp_z / exp_z.sum())\n p[-1] = 1 - sum(p[:-1])\n return p\n\nclass ReplayMemory:\n def __init__(self,capacity=1000):\n self.position = -1\n self.capacity = capacity\n self.memory = []\n\n def push(self, *args):\n if len(self.memory) < self.capacity:\n self.memory.append(args)\n self.position = (self.position + 1) % self.capacity\n else:\n self.memory[self.position] = args\n self.position = (self.position + 1) % self.capacity\n\n def sample(self,sample_size):\n return random.sample(self.memory, sample_size)\n\nclass Q_Net(torch.nn.Module):\n def __init__(self, lsize):\n super().__init__()\n self.layers = nn.ModuleList()\n self.n_layers = len(lsize) - 1\n for i in range(self.n_layers):\n self.layers.append(torch.nn.Linear(lsize[i], lsize[i+1]))\n\n def forward(self, x):\n for i in range(self.n_layers):\n x = self.layers[i](x)\n if i < self.n_layers-1:\n x = F.relu(x)\n return x\n\n def save(self, fn):\n torch.save(self.state_dict(), fn)\n\n def load(self, fn):\n self.load_state_dict(torch.load(fn))\n\nclass PlayerMLP:\n def __init__(self, casino):\n self.casino = casino\n self.nA = casino.get_action_space()\n self.nDS = casino.nDS\n self.nPS = casino.nPS\n self.nPA = casino.nPA\n self.nSnA = (self.nDS, self.nPS, self.nPA, self.nA)\n self.n_episode = 0\n self.pocket = 0\n self.make_net()\n\n #self.optimizer1 = optim.Adam(self.qf1.parameters(), lr=0.001, weight_decay=0)\n #self.optimizer2 = optim.Adam(self.qf2.parameters(), lr=0.001, weight_decay=0)\n #self.optimizer1 = optim.Adadelta(self.qf1.parameters(), lr=0.1, weight_decay=0)\n #self.optimizer2 = optim.Adadelta(self.qf2.parameters(), lr=0.1, weight_decay=0)\n #self.optimizer1 = optim.Adagrad(self.qf1.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer2 = optim.Adagrad(self.qf2.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer1 = optim.SparseAdam(self.qf1.parameters(), lr=0.001)\n #self.optimizer2 = optim.SparseAdam(self.qf2.parameters(), lr=0.001)\n self.optimizer1 = optim.Adamax(self.qf1.parameters(), lr=0.002, weight_decay=0)\n self.optimizer2 = optim.Adamax(self.qf2.parameters(), lr=0.002, weight_decay=0)\n #self.optimizer1 = optim.ASGD(self.qf1.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer2 = optim.ASGD(self.qf2.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer1 = optim.LBFGS(self.qf1.parameters(), lr=1)\n #self.optimizer2 = optim.LBFGS(self.qf2.parameters(), lr=1)\n #self.optimizer1 = optim.RMSprop(self.qf1.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer2 = optim.RMSprop(self.qf2.parameters(), lr=0.01, weight_decay=0)\n #self.optimizer1 = optim.Rprop(self.qf1.parameters(), lr=0.01)\n #self.optimizer2 = optim.Rprop(self.qf2.parameters(), lr=0.01)\n #self.optimizer1 = optim.SGD(self.qf1.parameters(), lr=0.01, nesterov = True, momentum = 0.1)\n #self.optimizer2 = optim.SGD(self.qf2.parameters(), lr=0.01, nesterov = True, momentum = 0.1)\n\n milestone = [5000, 10000,30000,50000,70000,90000,120000,160000,200000,250000,]\n\n self.lr_scheduler1 = optim.lr_scheduler.MultiStepLR(self.optimizer1, milestone, gamma=1/np.sqrt(10))\n self.lr_scheduler2 = optim.lr_scheduler.MultiStepLR(self.optimizer2, milestone, gamma=1/np.sqrt(10))\n #self.lr_scheduler1 = optim.lr_scheduler.LambdaLR(self.optimizer1, lr_lambda = lambda epoch: 1/math.sqrt((epoch+1)/1000))\n #self.lr_scheduler2 = optim.lr_scheduler.LambdaLR(self.optimizer2, lr_lambda = lambda epoch: 1/math.sqrt((epoch+1)/1000))\n #self.lr_scheduler1 = optim.lr_scheduler.ExponentialLR(self.optimizer1, gamma = 1+1e-5)\n #self.lr_scheduler2 = optim.lr_scheduler.ExponentialLR(self.optimizer2, gamma = 1+1e-5)\n #self.lr_scheduler1 = optim.lr_scheduler.CosineAnnealingLR(self.optimizer1, T_max=1000)\n #self.lr_scheduler2 = optim.lr_scheduler.CosineAnnealingLR(self.optimizer2, T_max=1000)\n\n self.batch_size = 1\n\n self.choice = 1\n\n self.test_episode = 0\n\n def make_net(self):\n H = 64\n lsize = [self.dimS(), H, H,H, self.nA]\n self.qf1 = Q_Net(lsize)\n self.qf2 = Q_Net(lsize)\n\n def load(self, fn):\n self.qf1.load(fn)\n\n def save(self, fn):\n self.qf1.save(fn)\n\n def dimS(self):\n return 13\n\n def get_state(self):\n s = self.casino.observe()\n s = torch.tensor(s, dtype=torch.float32)\n p = self.casino.peep()\n p = torch.tensor(p, dtype=torch.float32)\n s = torch.cat((s,p))\n return s\n\n def get_action(self, state, greedy=True):\n if greedy:\n with torch.no_grad():\n q = (self.qf1(state)+ self.qf2(state))/2\n q = q.cpu()\n q = q.numpy()\n a = q.argmax()\n else:\n a = np.random.choice(self.nA)\n return a\n\n def get_eps_greedy_action(self, state):\n eps = 1/math.sqrt(self.n_episode/10000)\n eps = min(eps, 0.5)\n p = np.random.random()\n if p > eps:\n with torch.no_grad():\n q = self.qf(state)\n q = q.cpu()\n q = q.numpy()\n a = q.argmax()\n else:\n a = np.random.choice(self.nA)\n return a\n\n def get_DQ_eps_action(self, state):\n eps = 1/math.sqrt(self.n_episode/10000)\n eps = min(eps, 0.5)\n p = np.random.random()\n if p > eps:\n with torch.no_grad():\n q1 = self.qf1(state)\n q2 = self.qf2(state)\n q = (q1+q2)/2\n q = q.cpu()\n q = q.numpy()\n a = q.argmax()\n else:\n a = np.random.choice(self.nA)\n return a\n\n def get_softmax_action(self, state,tau):\n with torch.no_grad():\n q = self.qf(state)\n q = q.cpu()\n q = q.numpy()\n soft_q = get_softmax(q,tau)\n a = np.random.choice(4,1,p=soft_q)\n return a\n\n def TD_update_Q(self, s,a,r,sp):\n s = torch.tensor(s)\n q = self.qf(s)[a]\n if sp is None:\n t = torch.tensor(float(r))\n else:\n sp = torch.tensor(sp)\n with torch.no_grad():\n t = r + self.qf(sp).max()\n #loss = F.mse_loss(q, t)\n loss = F.smooth_l1_loss(q, t)\n #loss = F.soft_margin_loss(q,t)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n def TD_update_DQ(self, s,a,r,sp):\n s = torch.tensor(s)\n\n if sp is None:\n t = torch.tensor(float(r))\n else:\n sp = torch.tensor(sp)\n with torch.no_grad():\n if self.choice == 1:\n t = r + self.qf2(sp).max()\n else:\n t = r + self.qf1(sp).max()\n if self.choice == 1:\n q = self.qf1(s)[a]\n\n #loss = F.l1_loss(q,t)\n loss = F.mse_loss(q, t)\n #loss = F.smooth_l1_loss(q, t)\n #loss = F.kl_div(q,t)\n #loss = F.multilabel_soft_margin_loss(q,t)\n\n #loss = F.poisson_nll_loss(q,t)\n #loss = F.cross_entropy(q,t)\n #loss = F.hinge_embedding_loss(q,t)\n #loss = F.multilabel_margin_loss(q,t)\n #loss = F.multi_margin_loss(q,t)\n #loss = F.nll_loss(q,t)\n #loss = F.soft_margin_loss(q,t)\n\n self.optimizer1.zero_grad()\n loss.backward()\n self.optimizer1.step()\n else:\n q = self.qf2(s)[a]\n\n #loss = F.l1_loss(q,t)\n loss = F.mse_loss(q, t)\n #loss = F.smooth_l1_loss(q, t)\n #loss = F.kl_div(q,t)\n #loss = F.multilabel_soft_margin_loss(q,t)\n\n #loss = F.poisson_nll_loss(q,t)\n #loss = F.cross_entropy(q,t)\n #loss = F.hinge_embedding_loss(q,t)\n #loss = F.multilabel_margin_loss(q,t)\n #loss = F.multi_margin_loss(q,t)\n #loss = F.nll_loss(q,t)\n #loss = F.soft_margin_loss(q,t)\n\n self.optimizer2.zero_grad()\n loss.backward()\n self.optimizer2.step()\n\n\n def Batch_update(self,batch_size):\n sample = self.Trans_Memory.sample(batch_size)\n for i in range(len(sample)):\n s,a,r,sp = sample[i]\n self.TD_update_DQ(s,a,r,sp)\n\n def reset_episode(self):\n self.n_episode += 1\n\n def run_episode1(self, batch_size):\n p = random.random()\n if p < 0.5:\n self.lr_scheduler1.step()\n self.choice = 1\n else:\n self.lr_scheduler2.step()\n self.choice = 2\n self.n_episode += 1\n self.casino.start_game()\n s = self.get_state()\n done = False\n while not done:\n #tau = math.sqrt(1/self.n_episode)\n #a = self.get_softmax_action(s,tau)\n #a = self.get_eps_greedy_action(s)\n a = self.get_DQ_eps_action(s)\n _, reward, done = self.casino.step(a)\n if done: sp = None\n else: sp = self.get_state()\n self.Trans_Memory.push(s,a,reward,sp)\n s = sp\n if len(self.Trans_Memory.memory) > batch_size*100:\n self.Batch_update(batch_size)\n\n\n def run_simulation(self, n_episode=1E7, max_time=6000000):\n stime = time.time()\n ip1 = 0\n self.Trans_Memory = ReplayMemory(1000)\n self.n_episode = 0\n\n while time.time() - stime < max_time:\n ip1 += 1\n if ip1 > n_episode: break\n self.run_episode1(self.batch_size)\n\n if ip1 % 10000 == 0:\n print (ip1, 'lr = %f'%((self.optimizer1.param_groups[0]['lr']+self.optimizer2.param_groups[0]['lr'])/2))\n w = self.test_performance(30000) * 100\n print(ip1, 'winning rate = ', w)\n print('--------------------------------------')\n #self.plot_Q()\n\n print(\"learning complete\")\n\n def get_all_state_tensor(self, p):\n S = torch.zeros((self.nDS * self.nPS * self.nPA, self.dimS()))\n k = 0\n for ds in range(self.nDS):\n for ps in range(self.nPS):\n for ua in range(self.nPA):\n S[k][0] = ds\n S[k][1] = ps\n S[k][2] = ua\n k += 1\n return S\n\n def plot_Q(self, p=None, fid=0):\n if p is None:\n p = np.zeros(10)\n p.fill(1 / 13)\n p[8] = 4 / 13\n S = self.get_all_state_tensor(p)\n with torch.no_grad():\n Q = self.qf(S)\n Q = Q.numpy()\n Q = Q.reshape(self.nSnA)\n pi = Q.argmax(-1)\n Q[0:2, :, :, :] = -2\n Q[:, 0:4, :, :] = -2\n Q[:, 22, :, :] = -2\n Q[:, 4:12, 1, :] = -2\n pi[0:2, :] = -2\n pi[:, 0:4, :] = -2\n pi[:, 22, :] = -2\n pi[:, 4:12, 1] = -2\n\n fig = plt.figure(fid, figsize=(7, 8), clear=True)\n for ua in range(self.nPA):\n for a in range(self.nA):\n self.plot_Qi(fig, Q, a, ua)\n self.plot_pi(fig, pi, ua)\n self.diff_Q(fig, Q, pi)\n plt.draw()\n plt.pause(1)\n\n def plot_Qi(self, fig, Q, a, ua):\n ax = fig.add_subplot(6, 2, 2 * a + ua + 1)\n ax.imshow(Q[:, :, ua, a], vmin=-2, vmax=1)\n\n def plot_pi(self, fig, pi, ua):\n ax = fig.add_subplot(6, 2, 9 + ua)\n ax.imshow(pi[:, :, ua], vmin=-2, vmax=self.nA - 1)\n\n def diff_Q(self, fig, Q, pi):\n if 'pi_old' in dir(self):\n PIdiff = (pi != self.pi_old)\n Qdiff = (Q - self.Q_old)\n print(\"PI diff = %d\" % (PIdiff.sum()))\n print('Qdiff max=%.3f, min=%.3f' % (Qdiff.max(), Qdiff.min()))\n ax = fig.add_subplot(6, 2, 11)\n ax.imshow(PIdiff[:, :, 0])\n ax = fig.add_subplot(6, 2, 12)\n ax.imshow(PIdiff[:, :, 1])\n self.Q_old = Q\n self.pi_old = pi\n\n def update_pocket(self, reward):\n self.pocket += reward\n\n def play_game(self):\n self.test_episode += 1\n self.casino.start_game()\n done = False\n while not done:\n s = self.get_state()\n a = self.get_action(s, greedy=True)\n _, reward, done = self.casino.step(a)\n self.update_pocket(reward)\n return reward\n\n def print_epg_wr(self, n_games):\n epg = self.pocket / n_games\n wr = (epg + 1) / 2\n std_wr = np.sqrt(wr * (1 - wr) / n_games)\n print(\"# of game=%d, player's pocket=%d, E/G=%.5f, WR=%.5f%% +- %.5f\"\n % (n_games, self.pocket, epg, wr * 100, std_wr * 100))\n return wr\n\n def test_performance(self, n_games):\n self.pocket = 0\n n_10 = n_games / 10\n for i in range(1, n_games + 1):\n reward = self.play_game()\n if n_games > 100000 and i % n_10 == 0:\n self.print_epg_wr(i)\n print (\"Final result\")\n return self.print_epg_wr(n_games)\n","sub_path":"RL(Reinforcement Learning)/Blackjack/other Players/NNPlayer_Optimizer_selection.py","file_name":"NNPlayer_Optimizer_selection.py","file_ext":"py","file_size_in_byte":13586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"496298004","text":"class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n \nclass creatTree:#先序遍历创建二叉树\n def __init__(self, arr):\n self.arr = arr\n self.root = None\n self.creatXian(0,None)\n def creatXian(self, k, Node):\n if k == 0:\n self.root = TreeNode(self.arr[k])\n self.creatXian(k+1,self.root)\n else:\n #Node.left\n if self.arr[k] is None:\n Node.left = None\n #Node.right\n if self.arr[k+1] is None:\n Node.right = None\n return k+1\n else:\n Node.right = TreeNode(self.arr[k+1])\n n = self.creatXian(k+2,Node.right)\n return n\n else:\n Node.left = TreeNode(self.arr[k])\n n = self.creatXian(k+1,Node.left)\n\n #Node.right\n if self.arr[n+1] is None:\n Node.right = None\n return n+1\n else:\n Node.right = TreeNode(self.arr[n+1])\n n = self.creatXian(n+2,Node.right)\n return n\n \na = creatTree([3,9,None,None,20,15,None,None,7,None,None])\nclass Solution:\n def __init__(self, root):\n self.root = root\n self.load = []\n self.averageOfLevels([self.root])\n print(self.load)\n\n def averageOfLevels(self, arr):\n temp = []\n sumnumb = 0\n for i in range(len(arr)):\n sumnumb += arr[i].val\n if arr[i].left is not None:\n temp.append(arr[i].left)\n if arr[i].right is not None:\n temp.append(arr[i].right)\n self.load.append(sumnumb/len(arr))\n if len(temp) != 0:\n self.averageOfLevels(temp)\n else:\n return\n","sub_path":"code/二叉树每层平均值.py","file_name":"二叉树每层平均值.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"615748589","text":"class UnionFind:\r\n\r\n def __init__(self, n):\r\n self.table = [-1] * (n + 1)\r\n self.size = [1] * (n + 1)\r\n\r\n def merge(self, r1, r2):\r\n self.table[r1] = r2\r\n self.size[r2] += self.size[r1]\r\n self.size[r1] = 0\r\n\r\n def find_root(self, k):\r\n path = []\r\n curr = k\r\n while self.table[curr] != -1:\r\n path.append(curr)\r\n curr = self.table[curr]\r\n for i in path:\r\n self.table[i] = curr\r\n return curr\r\n\r\n\r\ndef solve(string):\r\n n, m, *ab = map(int, string.split())\r\n ab = ab[::-1]\r\n ans = [n * (n - 1) // 2]\r\n uf = UnionFind(n)\r\n for _b, _a in zip(ab[::2], ab[1::2]):\r\n ra = uf.find_root(_a)\r\n rb = uf.find_root(_b)\r\n if ra == rb:\r\n ans.append(ans[-1])\r\n continue\r\n ans.append(ans[-1] - uf.size[ra] * uf.size[rb])\r\n uf.merge(ra, rb)\r\n return \"\\n\".join([str(a) for a in ans[:-1][::-1]])\r\n\r\n\r\nif __name__ == '__main__':\r\n n, m = map(int, input().split())\r\n print(solve('{} {}\\n'.format(n, m) + '\\n'.join([input() for _ in range(m)])))","sub_path":"Source Codes/AtCoder/abc120/D/4902363.py","file_name":"4902363.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"108112611","text":"from webalchemy.Stacker import Stacker\nfrom sympy import *\n\nexamples = [\n (r'Take the derivative of \\(\\sin{(x)}e^x\\)', 'diff(sin(x)*exp(x), x)'),\n (r'Compute \\(\\int(e^x\\sin{(x)} + e^x\\cos{(x)})\\,dx\\)', 'integrate(exp(x)*sin(x) + exp(x)*cos(x), x)'),\n (r'Compute \\(\\int_{-\\infty}^\\infty \\sin{(x^2)}\\,dx\\)', 'integrate(sin(x**2), (x, -oo, oo))'),\n (r'Find \\(\\lim_{x\\to 0}\\frac{\\sin{(x)}}{x}\\)', 'limit(sin(x)/x, x, 0)'),\n (r'Solve \\(x^2 - 2 = 0\\)', 'solve(x**2 - 2, x)'),\n (r'Solve the differential equation \\(y'' - y = e^t\\)', '''y = Function('y'); dsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))'''),\n (r'Find the eigenvalues of \\(\\left[\\begin{smallmatrix}1 & 2\\\\2 & 2\\end{smallmatrix}\\right]\\)', 'Matrix([[1, 2], [2, 2]]).eigenvals()'),\n (r'Rewrite the Bessel function \\(J_{\\nu}\\left(z\\right)\\) in terms of the spherical Bessel function \\(j_\\nu(z)\\)','besselj(nu, z).rewrite(jn)')\n]\n\nfunctions = ['diff', 'integrate', 'limit', ]\n\nclass MathExplorer:\n \"\"\"Application to explore math from the browser\"\"\"\n\n include = ['//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',\n '//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js',\n 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML']\n stylesheets = ['//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css']\n\n def initialize(self, **kwargs):\n self.rdoc = kwargs['remote_document']\n s = Stacker(self.rdoc.body)\n with s.div(cls='container'), s.div(cls='row'), s.div(cls='col-md-12 page-header'):\n with s.h1(text=\"The Math Exploerer\"):\n s.small(text=\" use it for... uhm... exploring math?\")\n with s.div(cls='row'):\n # left column\n with s.div(cls='col-md-7'), s.div(cls='row'):\n with s.div(cls='col-md-12 panel panel-default'):\n self.pbody = s.div(cls='panel-body', style={'minHeight':'500px', 'overflowY':'auto'})\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='well'):\n self.inp = s.input(cls='form-control', att={'placeholder': \"Enter Math here (see examples)\"})\n self.inp.events.add(keydown=self.execute, translate=True)\n # right column\n with s.div(cls='col-md-5'):\n\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='panel panel-success'), s.div(text=\"Examples:\", cls='panel-heading'):\n s.button(text=\"toggle\", att={'data-toggle':\"collapse\", 'data-target':\"#examples_body\"}, cls=\"btn btn-xs btn-default pull-right\")\n with s.div(customvarname='examples_body', cls='panel-body collapse in'):\n with s.ul():\n for desc, codes in examples:\n with s.li(text=desc.replace('\\\\', '\\\\\\\\')):\n for code in codes.split(';'):\n s.br()\n s.code(text=code).events.add(click=lambda: self.inp.prop(value=code))\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='panel panel-info'):\n s.div(text=\"Symbols:\", cls='panel-heading')\n s.div(text=\"x\", cls='panel-body')\n with s.div(cls='row'), s.div(cls='col-md-12'), s.div(cls='panel panel-info'):\n s.div(text=\"Functions:\", cls='panel-heading')\n s.div(text=\"bla bla\", cls='panel-body')\n self.rdoc.JS('MathJax.Hub.Queue([\"Typeset\",MathJax.Hub, \"examples_body\"]);')\n\n def execute(e):\n if e.keyCode == weba.KeyCode.ENTER:\n rpc(self.calc_with_sympy, self.value)\n\n def calc_with_sympy(self, sender_id, text):\n try:\n self.pbody.element(p=str(sympify(text)))\n except Exception as e:\n self.pbody.element('p').prop.innerHTML = str(e).replace(\"\\n\", ' ')\n\n\nif __name__ == \"__main__\":\n from webalchemy import server\n from math_explorer import MathExplorer\n server.run(MathExplorer)\n\n\n\n\n","sub_path":"examples/math_explorer/math_explorer.py","file_name":"math_explorer.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"194049743","text":"#!python\r\n\r\nfrom tkinter import *\r\n\r\nclass Application(Frame):\r\n\tdef say_hi(self):\r\n\t\tprint(\"hi there, everyone!\")\r\n\r\n\tdef createWidgets(self):\r\n\t\tself.Forward = Button(self, text=\"/\\\\\", command=lambda: self.control(\"F\"), font=(20))\r\n\t\tself.Reverse = Button(self, text=\"V\", command=lambda: self.control(\"R\"), font=(20))\r\n\t\tself.Left = Button(self, text=\"<\", command=lambda: self.control(\"L\"), font=(20))\r\n\t\tself.Right = Button(self, text=\">\", command=lambda: self.control(\"R\"), font=(20))\r\n\t\tself.QUIT = Button(self, text=\"QUIT\", fg=\"red\", command=self.quit)\r\n\t\tself.QUIT.focus()\r\n\t\t\r\n\r\n\t\tself.Forward.grid(column=1, row=0)\r\n\t\tself.Left.grid(column=0, row=1)\r\n\t\tself.QUIT.grid(column=1, row=1)\r\n\t\tself.Right.grid(column=2, row=1)\r\n\t\tself.Reverse.grid(column=1, row=2)\r\n\r\n#\t\tself.hi_there = Button(self)\r\n#\t\tself.hi_there[\"text\"] = \"Hello\",\r\n#\t\tself.hi_there[\"command\"] = self.say_hi\r\n\r\n#\t\tself.hi_there.pack({\"side\": \"left\"})\r\n\r\n\tdef __init__(self, master=None):\r\n\t\tFrame.__init__(self, master)\r\n\t\tself.pack()\r\n\t\tself.createWidgets()\r\n\r\n\tdef control(self, command):\r\n\t\tprint(command)\r\n\r\ndef main():\r\n\troot = Tk()\r\n\tapp = Application(master=root)\r\n\tapp.mainloop()\r\n\troot.destroy()\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"tk/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"185528678","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 12 21:25:25 2018\n\n@author: Thinkpad\n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom driver import driver\n\ncap=cv2.VideoCapture(0)\nd=driver()\nd.setStatus(mode=\"speed\")\n\n#*****************************图像处理部分***********************************\n#***************************************************************************\n\ndef ImgPro():\n #img = cv2.imread(\"F://testimages//road2.jpg\", cv2.IMREAD_COLOR) \n img=cap.read()\n cv2.imshow(\"color\", img )\n dst=img.copy()\n\n size=np.shape(img)\n height=size[0]\n width=size[1]\n\n grayImg=cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)\n #cv2.imshow(\"grayImg\",grayImg)\n medianImg= cv2.medianBlur(grayImg,3)\n #cv2.imshow(\"medianImg\",medianImg)\n ret,binary=cv2.threshold(medianImg,80,255,cv2.THRESH_BINARY_INV)\n #ret2,binary = cv2.threshold(medianImg,0,100,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n #cv2.imshow(\"binary\",binary)\n kernel = np.ones((2,2),np.uint8)\n opening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)\n #cv2.imshow(\"open\",opening)\n\n #近处参考点用于控制当拍动作\n rec_sum=0\n rec_num=0\n for i in range(height-3,height-1) :\n for j in range(width-5):\n if (opening[i][j]==255 and opening[i][j+1]==255 and opening[i][j+2]==255 and opening[i][j+3]==255 and opening[i][j+4]==255):\n rec_num+=1\n rec_sum+=j\n ref=rec_sum/rec_num\n \n p1=(ref,0)\n p2=(ref,height)\n cv2.line(opening,p1,p2,(255))\n #cv2.imshow(\"opening\",opening)\n \n #远处参考点用于预测前方路段形状\n rec_sum=0\n rec_num=0\n pre_ref=0\n for i in range(height-43,height-40) :\n for j in range(width-5):\n if (opening[i][j]==255 and opening[i][j+1]==255 and opening[i][j+2]==255 and opening[i][j+3]==255 and opening[i][j+4]==255):\n rec_num+=1\n rec_sum+=j\n pre_ref=rec_sum/rec_num\n p1=(pre_ref,0)\n p2=(pre_ref,height)\n cv2.line(opening,p1,p2,(255))\n cv2.imshow(\"opening\",opening)\n \n #sign_detector\n flag=0\n \n \n \n if cv2.waitKey(1) & 0xFF==ord('p'):\n cv2.imwrite('test'+str(1)+'.jpg',img)\n \n \n cv2.waitKey(0) \n cv2.destroyAllWindows()\n \n return ref,pre_ref,flag\n\n#***************************main**********************************************\nwhile(1):\n ref,pre_ref,flag=ImgPro()\n if (flag==1):\n d.setStatus(motor=0.0, servo=0.0, dist=0x00, mode=\"stop\")\n break\n \n if (pre_ref<160 or pre_ref>480):\n sm=0.2\n else:\n sm=0.5\n \n if (ref<352 & ref>288):\n st=0\n else:\n st=-(320-ref)*0.02\n \n d.setStatus(motor = sm, servo = st)\n \n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"cruise.py","file_name":"cruise.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"585696149","text":"# -*- coding: utf-8 -*-\nfrom core.mlang.forms import TranslatedForm\nfrom core.mlang.utils import translate\nfrom django.utils.translation import get_language\nfrom .models import Page\nfrom django.contrib import admin\n\n\nclass PageAdmin(admin.ModelAdmin):\n form = TranslatedForm\n\n suit_form_tabs = (\n (\"general\", 'General'),\n (\"seo\", \"Seo\"),\n (\"content\", \"Content\"),\n )\n\n fieldsets = [\n (None, {\n 'classes': ('suit-tab suit-tab-general',),\n 'fields': ['code', 'parent']\n }),\n (None, {\n 'classes': ('suit-tab suit-tab-seo',),\n 'fields': [\"title\", \"description\", \"keywords\"]}),\n (None, {\n 'classes': ('suit-tab suit-tab-content',),\n 'fields': ['content']}),\n ]\n\n def get_queryset(self, request):\n qs = super(PageAdmin, self).get_queryset(request).filter(id__isnull=False)\n return translate(qs, get_language(), exclude=['description', 'keywords', 'content'])\n\n\nadmin.site.register(Page, PageAdmin)","sub_path":"apps/flatpages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"180084634","text":"#coding:utf-8\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.utils import timezone\nfrom .models import *\nimport json\nimport logging\nimport datetime\nimport time\n\ndef index(request):\n return HttpResponse(u\"欢迎光临本站!\")\n\ndef home(request):\n subjectlist = []\n pageIndex = int(request.GET.get('pageIndex',1))\n pagesize = 15\n subjectlist = Subject.objects.all()[(pageIndex-1)*pagesize:pageIndex*pagesize-1]\n pagetotal = (Subject.objects.all().count()-1)/pagesize + 1\n if pagetotal==0:\n pagetotal = 1\n\n pageinfo = {\n 'pageIndex':pageIndex,\n 'pageprev2':False,\n 'pageprev':False,\n 'pagenext':False,\n 'pagenext2':False\n }\n if pageIndex-2 > 0:\n pageinfo['pageprev2']=pageIndex-2\n if pageIndex-1 > 0:\n pageinfo['pageprev']=pageIndex-1\n if pageIndex < pagetotal:\n pageinfo['pagenext'] = pageIndex+1\n if pageIndex+1 < pagetotal:\n pageinfo['pagenext2']=pageIndex+2\n\n return render(request,'vote.html',{'subjectlist':subjectlist,'pageinfo':pageinfo})\n # logging.debug(request.session['username'])\n\ndef createvote(request):\n subject = request.GET['subject']\n deadline = request.GET['deadline']\n options = request.GET.getlist('options[]')\n # print subject\n ret = {'status_code':'success'}\n for item in options:\n # print item\n if item==\"\":\n ret = {'status_code':'fail'}\n if subject == \"\" or deadline==\"\":\n ret = {'status_code':'fail'}\n if ret['status_code'] == 'fail':\n return HttpResponse(json.dumps(ret),content_type='application/json')\n # print deadline\n t= time.strptime(deadline, \"%Y-%m-%d - %H:%M\")\n y,m,d,h,mm = t[0:5]\n obj_time = datetime.datetime(y,m,d,h,mm)\n # print obj_time\n obj_sub = Subject.objects.create(title=subject,deadline=obj_time)\n for option in options:\n obj_opt = Option.objects.create(subject=obj_sub,name=option)\n \n return HttpResponse(json.dumps(ret),content_type='application/json')\n\ndef votequery(request):\n ret = {'vote_status':'ok'}\n subject_id = request.GET['subject_id']\n obj_sub = Subject.objects.get(id=subject_id)\n # time_now = datetime.datetime.now()\\\n time_now = timezone.now()\n if time_now >= obj_sub.deadline:\n ret['vote_status'] = 'over_deadline'\n return HttpResponse(json.dumps(ret),content_type='application/json')\n options = Option.objects.filter(subject=obj_sub)\n result = VoteRecord.objects.filter(option__in=options,user=request.user)\n if len(result)==1:\n ret['vote_status'] = 'vote_already'\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\n \ndef optionquery(request):\n options = []\n subject_id = request.GET['subject_id']\n obj_sub = Subject.objects.get(id=subject_id)\n obj_opt_list = Option.objects.filter(subject=obj_sub)\n for obj in obj_opt_list:\n entity = {}\n entity['id'] = obj.id\n entity['name'] = obj.name\n options.append(entity)\n ret = {'options':options}\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\ndef votesubmit(request):\n option_id = request.GET.get('option_id',None)\n ret = {'status_code':'fail'}\n if option_id == None:\n ret = {'status_code':'nopara'}\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\n obj_opt = Option.objects.get(id=option_id)\n result = VoteRecord.objects.get_or_create(user=request.user,option=obj_opt)\n\n #重新计算主题得票王\n obj_sub = obj_opt.subject\n options = Option.objects.filter(subject=obj_sub)\n opt_hot = \"\"\n num_max = 1\n for option in options:\n num = VoteRecord.objects.filter(option=option).count()\n if num > num_max:\n num_max = num\n opt_hot = option.name\n elif num == num_max:\n opt_hot = opt_hot + \" \" + option.name\n obj_sub.hot = opt_hot\n # print opt_hot\n # print obj_sub.hot\n obj_sub.save()\n # print 'after save'\n # obj_sub = obj_opt.subject\n # print obj_sub.hot\n\n if result[1]==True:\n ret['status_code']='success'\n return HttpResponse(json.dumps(ret),content_type='application/json')\n \ndef voteresult(request):\n subject_id = request.GET['subject_id']\n result = []\n obj_sub = Subject.objects.get(id=subject_id)\n obj_opt_list = Option.objects.filter(subject=obj_sub)\n for obj_opt in obj_opt_list:\n count = VoteRecord.objects.filter(option=obj_opt).count()\n entity = {}\n entity['name'] = obj_opt.name\n entity['count'] = count\n result.append(entity)\n ret = {'result':result}\n return HttpResponse(json.dumps(ret),content_type='application/json')\n\n\ndef test(request):\n return HttpResponse(request.user.username)\n # logging.debug(request.session['username'])\n\n# Create your views here.\n","sub_path":"vote/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"604383002","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'junk.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$','views.dashboard'),\n url(r'^facebook_connect/$', 'views_fb.facebook_connect'),\n url('^accounts/facebook_callback/$','views_fb.facebook_callback'),\n url(r'^twitter_connect/$','views_tw.twitter_connect'),\n url(r'^accounts/twitter_callback/$','views_tw.twitter_callback'),\n url('^accounts/login/$','views_login.login_screen'),\n url('^accounts/create/$','views_login.create'),\n url('^confirmed/$','views_login.confirmed'),\n url('^accounts/logout/$','views_login.logout_view'),\n url(r'^in_connect/$','views_in.in_connect'),\n url(r'^accounts/in_callback/$','views_in.in_callback'),\n url(r'^g_connect/$','views_g.g_connect'),\n url(r'^accounts/g_callback/$','views_g.g_callback'),\n url(r'^instagram_connect/$','views_instagram.instagram_connect'),\n url(r'^accounts/instagram_callback/$','views_instagram.instagram_callback'), \n\n url(r'^upload/$','views_upload.upload'),\n url(r'^upload_process/$','views_upload.upload_process'),\t\n\n #custom tab for FB Biz page\n url(r'^fb_custom_tab/$','views_fb_custom_tab.custom_tab'),\n\n url(r'^ajax_call/$','views_ajax.ajax_call'),\n\n)\n","sub_path":"junk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"546861293","text":"'''\nACFun is a Chinese Video sharing website\n'''\n\nfrom .common import InfoExtractor\nimport re\nfrom .sina import SinaIE\n\nclass ACFunIE(InfoExtractor):\n _VALID_URL = r'^https?://(?:www\\.)?acfun\\.tv/v/(?P[a-zA-Z0-9]+)'\n _TESTS = [\n {\n u'url' : u'http://www.acfun.tv/v/ac976407',\n u'file' : u'pv 22-123189263.flv'\n }\n ]\n\n def _real_extract(self, url):\n mobj = re.match(self._VALID_URL, url)\n\n vid = mobj.group('id')\n webpage = self._download_webpage(url, vid)\n vid = self._html_search_regex(\n r'data-vid\\=\\\"([0-9]*)\\\"', webpage, u'vid')\n\n info = self._download_json(\"http://www.acfun.tv/video/getVideo.aspx?id=%s\" % vid, vid)\n if info['sourceType'] == \"sina\":\n return self.url_result(\"http://video.sina.com.cn/something/?vid=%s\" % info['sourceId'])\n elif info['sourceType'] == \"yoku\":\n return self.url_result(\"http://v.youku.com/v_show/id_%s.html\" % info['sourceId'])\n elif info['sourceType'] == \"tudou\":\n raise Error('tudou is not supported yet via acfun')\n elif info['sourceType'] == \"qq\":\n raise Error('qq downloading is not supported via youtube-dl')\n else:\n raise Error('source type not supported: %s' % info['sourceType'])\n","sub_path":"youtube_dl/extractor/acfun.py","file_name":"acfun.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"219924521","text":"\"\"\"Calico utility script.\n\nCalico utility script\n\"\"\"\n\nimport yaml\n\n# needed this to execute from the command line, otherwise received an ImportError\n# import os, sys\n# sys.path.insert(0, os.path.abspath(\"..\"))\n\nimport interfaces\nfrom utils import ConfigReader\nfrom utils import jm_general\nfrom snmp import poll\nfrom snmp import snmp_manager\nfrom snmp import snmp_info\nfrom web import ws_device\n\nimport urllib.request\nimport string\nimport os\n\n# from pprint import pprint\n\nOUI_URL = 'http://standards-oui.ieee.org/oui.txt'\nOUI_YAML_FILE_NAME = \"oui_data.yaml\"\n\nCACHE_FILE_PATH = '{}/bin/oui.txt'.format(os.getcwd())\nFILE_LOCATION = '{}/data/aux/{}'.format(os.getcwd(), OUI_YAML_FILE_NAME)\n\n\ndef main():\n \"\"\"Main Function.\n\n Args:\n None\n Returns:\n None\n \"\"\"\n # Initialize key variables\n additional_help = \"\"\"\\ \n\tUtility script for the project.\n\t\"\"\"\n\n # Process the CLI\n cli_object = interfaces.Cli(additional_help=additional_help)\n cli_args = cli_object.args()\n\n # Process the config\n config = ConfigReader(cli_args.directory)\n\n # Show configuration data\n if cli_args.mode == 'config':\n do_config(cli_args, config)\n\n # Show interesting information\n if cli_args.mode == 'test':\n do_test(cli_args, config)\n\n # Process hosts\n if cli_args.mode == 'poll':\n do_poll(config, cli_args.verbose)\n\n # Create pages\n if cli_args.mode == 'pagemaker':\n do_pages(config, cli_args.verbose)\n\n # Get vendor OUI MAC addresses\n if cli_args.mode == 'oui':\n do_oui(cli_args, config)\n\n\ndef do_config(cli_args, config):\n \"\"\"Process 'config' CLI option.\n\n Args:\n connectivity_check: Set if testing for connectivity\n Returns:\n None\n \"\"\"\n # Show hosts if required\n if cli_args.hosts is True:\n print('hosts:')\n print(yaml.dump(config.hosts(), default_flow_style=False))\n\n # Show hosts if required\n if cli_args.snmp_auth is True:\n print('snmp_auth:')\n print(yaml.dump(config.snmp_auth(), default_flow_style=False))\n\n\ndef do_test(cli_args, config):\n \"\"\"Process 'test' CLI option.\n\n Args:\n connectivity_check: Set if testing for connectivity\n Returns:\n None\n \"\"\"\n # Show host information\n validate = snmp_manager.Validate(cli_args.host, config.snmp_auth())\n snmp_params = validate.credentials()\n snmp_object = snmp_manager.Interact(snmp_params)\n\n if bool(snmp_params) is True:\n print('\\nValid credentials found:\\n')\n print(yaml.dump(snmp_params, default_flow_style=False))\n print('\\n')\n\n # Get SNMP data and print\n status = snmp_info.Query(snmp_object)\n yaml_data = status.everything()\n print(yaml_data)\n else:\n # Error, host problems\n log_message = (\n 'Uncontactable host %s or no valid SNMP '\n 'credentials found for it.') % (cli_args.host)\n jm_general.logit(1006, log_message)\n\n\ndef do_pages(config, verbose=False):\n \"\"\"Process 'pagemaker' CLI option.\n\n Args:\n config: Configuration object\n verbose: Verbose output if True\n Returns:\n None\n \"\"\"\n # Poll\n ws_device.make(config, verbose)\n\n\ndef do_poll(config, verbose=False):\n \"\"\"Process 'run' CLI option.\n\n Args:\n config: Configuration object\n verbose: Verbose output if True\n Returns:\n None\n \"\"\"\n # Poll\n poll.snmp(config, verbose)\n\n\ndef do_oui(cli_args, config):\n \"\"\"\n\n Converts the groups of addresses that are assigned to NIC manufacturers based on the first 3 bytes of the address\n into a YAML file stored in data/aux in directory\n\n :param config:\n :param verbose:\n :return: None\n \"\"\"\n\n oui_data = {}\n if cli_args.inet:\n print('Reading OUI data from url:{}'.format(OUI_URL))\n response = urllib.request.urlopen(OUI_URL)\n # This is a very timely(>10 mins) operation\n data = response.read()\n data = data.split(\"\\n\")\n for line in data:\n hex_value = line[:6]\n if all(x in string.hexdigits for x in hex_value):\n organization = line[6:].replace(\"(base 16)\", \"\").strip().title()\n oui_data[hex_value.lower()] = organization\n else:\n print('Reading OUI MAC Address data from local cache file in bin')\n with open(CACHE_FILE_PATH, 'r') as file_data:\n for line in file_data:\n hex_value = line[:6]\n if all(x in string.hexdigits for x in hex_value):\n organization = line[6:].replace(\"(base 16)\", \"\").strip().title()\n oui_data[hex_value.lower()] = organization\n with open(FILE_LOCATION, 'wt+') as f:\n yaml.dump(oui_data, f, default_flow_style=False)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"infoset/toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"528998823","text":"\"\"\"\n3-way quicksort: Python implementation\n\nDuplicate keys\nMergesort with duplicate keys. Always between 1/2 NlgN and NlgN compares\n\nQuicksort with duplicate keys. The classic algorithm goes quadratic unless partitioning stops on equal keys\nRecommended: Stop scan on items equal to the partitioning item\nConsequence: ~NlgN compares when all keys equal\n\nBottom line: Randomized quicksort with 3-way partitioning reduces running time from linearithmic to linear in a broad class of applications.\nQuicksort with 3-way partitioning is most effective when the input array has a few distinct items?\n\nDijkstra 3-way partitioning\n\nEngineering a system sort\nBasic algorithm - quick sort\n - Cutoff to insertion sort for small subarrays\n - Partitioning scheme: 3-way partitioning\n - Partitioning items\n Large arrays: middle entry\n medium arrays: median of 3\n large arrays: Tukey's ninther\n\"\"\"\n\ndef quicksort(a, lo, hi):\n \"\"\"\n 3-way quicksort: Python implementation\n :param a: Array\n :param lo: low Index\n :param hi: high index\n \"\"\"\n if hi <= lo:\n return\n lt, gt = lo, hi\n i = lo\n while i <= gt:\n if a[i] < a[lt]:\n a[lt],a[i] = a[i],a[lt]\n lt += 1\n i += 1\n elif a[i] > a[lo]:\n a[gt],a[i] = a[i],a[gt]\n gt -= 1\n else:\n i += 1\n\n quicksort(a, lo, lt - 1)\n quicksort(a, gt + 1, hi)\n\n # assert isSorted(a) # Postcondition: a is sorted\n\n\ndef isSorted(a, asc=True):\n \"\"\"\n Check if an array is sorted\n :param a: array\n :param asc: ascending or descending\n :return: boolean\n \"\"\"\n s = 2*int(asc) - 1 # sign: int(True)=1 => 2*1-1 = 1\n\n for i in range(len(a)-1):\n if s * a[i] > s * a[i+1]:\n return False\n return True\n\n\ndef test_quicksort():\n import random\n\n a = [6,2,9,2,5]\n a_sorted = [2,2,5,6,9]\n random.shuffle(a) # Shuffle array only onсу\n quicksort(a, 0, len(a)-1)\n print(\"Test\", \"1.\", \"OK\" if a == a_sorted else \"Failed\")\n print()\n\n b = [1,0,0,0,0]\n b_sorted = [0,0,0,0,1]\n random.shuffle(b) # Shuffle array only onсу\n quicksort(b, 0, len(b)-1)\n print(\"Test\", \"2.\", \"OK\" if b == b_sorted else \"Failed\")\n print()\n\n c = [1]\n c_sorted = [1]\n random.shuffle(c)\n quicksort(c, 0, len(c)-1)\n print(\"Test\", \"3.\", \"OK\" if c == c_sorted else \"Failed\")\n print()\n\n\ndef test_isSorted():\n inp = [[0, 1, 2 , 3, 4], [6, 2, 9, 2, 5]]\n out = [True, False]\n for i in range(len(inp)):\n test_res = isSorted(inp[i])\n print(\"Test\", i + 1, \":\", \"OK\" if test_res == out[i] else \"Failed\")\n print()\n\n\nif __name__ == '__main__':\n print('test_quicksort')\n test_quicksort()\n\n print('test_isSorted')\n test_isSorted()\n","sub_path":"vladvvtesla/week03_MergeSort_QuickSort/2.imp_3-way-quicksort.py","file_name":"2.imp_3-way-quicksort.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"237734353","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom xsdata.models.datatype import XmlPeriod\nfrom travelport.models.phone_number_history_2 import PhoneNumberHistory2\nfrom travelport.models.type_structured_address_5 import TypeStructuredAddress5\n\n__NAMESPACE__ = \"http://www.travelport.com/schema/uprofile_v37_0\"\n\n\n@dataclass\nclass TypePaymentCardHistory2:\n \"\"\"\n Container for all credit and debit card information.\n\n Parameters\n ----------\n phone_number_history\n billing_address\n The address to where the billing statements for this card are sent.\n Used for address verification purposes.\n type_value\n The 2 letter credit/ debit card type.\n number\n exp_date\n The Expiration date of this card in YYYY-MM format.\n name\n The name as it appears on the card.\n cvv\n Card Verification Code\n approval_code\n This code is optional for an authorization process from the Credit\n Card company directly,optional for some of the CCH carriers.\n \"\"\"\n class Meta:\n name = \"typePaymentCardHistory\"\n\n phone_number_history: None | PhoneNumberHistory2 = field(\n default=None,\n metadata={\n \"name\": \"PhoneNumberHistory\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.travelport.com/schema/uprofile_v37_0\",\n }\n )\n billing_address: None | TypeStructuredAddress5 = field(\n default=None,\n metadata={\n \"name\": \"BillingAddress\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.travelport.com/schema/uprofile_v37_0\",\n }\n )\n type_value: None | str = field(\n default=None,\n metadata={\n \"name\": \"Type\",\n \"type\": \"Attribute\",\n \"min_length\": 2,\n \"max_length\": 2,\n }\n )\n number: None | str = field(\n default=None,\n metadata={\n \"name\": \"Number\",\n \"type\": \"Attribute\",\n \"min_length\": 13,\n \"max_length\": 128,\n }\n )\n exp_date: None | XmlPeriod = field(\n default=None,\n metadata={\n \"name\": \"ExpDate\",\n \"type\": \"Attribute\",\n }\n )\n name: None | str = field(\n default=None,\n metadata={\n \"name\": \"Name\",\n \"type\": \"Attribute\",\n \"max_length\": 128,\n }\n )\n cvv: None | str = field(\n default=None,\n metadata={\n \"name\": \"CVV\",\n \"type\": \"Attribute\",\n \"max_length\": 4,\n }\n )\n approval_code: None | str = field(\n default=None,\n metadata={\n \"name\": \"ApprovalCode\",\n \"type\": \"Attribute\",\n \"min_length\": 1,\n \"max_length\": 16,\n }\n )\n","sub_path":"travelport/models/type_payment_card_history_2.py","file_name":"type_payment_card_history_2.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"219547671","text":"import ROOT\nimport os\n\nclass Workflow_Handler:\n\n def __init__(self,signalname, subprocess=\"//\"):\n\n ##Where the root files are\n self.subprocess = subprocess\n\n self.norm_filename = \"rootfiles/\" + self.subprocess + \"Normalizations_table.txt\"\n self.dir_back_input = \"rootfiles/\" + self.subprocess + \"backgrounds/\"\n self.dir_data_input = \"rootfiles/\" + self.subprocess + \"data/\" \n\n self.sig_samplename = signalname\n self.sig_filename = \"rootfiles/\" + self.subprocess + \"signals/\" + \"HAA4bAnalysis_\" + self.sig_samplename + \".root\"\n\n def get_normalizations_map(self):\n in_file = open(self.norm_filename,\"r\")\n norm_map = dict()\n\n for line in in_file:\n data_norm = line.split()\n norm_map[data_norm[0]] = float(data_norm[1])\n\n return norm_map\n\n # get the sample names and signal names\n def get_samples_names(self, Add_Signal=True):\n list_dirs_bkg = os.listdir(self.dir_back_input)\n samplename_list = []\n\n for dirname in list_dirs_bkg:\n tmp_samplename = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_samplename2 = tmp_samplename.replace(\".root\",\"\")\n samplename_list.append(tmp_samplename2)\n\n if Add_Signal:\n samplename_list.append(self.sig_samplename)\n return samplename_list \n\n # get data sample names\n def get_dataSample_names(self):\n list_dirs_data = os.listdir(self.dir_data_input)\n dataName_list = []\n\n for dirname in list_dirs_data:\n tmp_dataName = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_dataName2 = tmp_dataName.replace(\".root\",\"\")\n dataName_list.append(tmp_dataName2)\n\n return dataName_list\n\n # get the corresponding root files for the background and signal sample names\n def get_root_files(self,Add_Signal=True):\n list_dirs_bkg = os.listdir(self.dir_back_input)\n root_file = dict()\n\n for dirname in list_dirs_bkg:\n tmp_samplename = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_samplename2 = tmp_samplename.replace(\".root\",\"\")\n root_file[tmp_samplename2] = ROOT.TFile(self.dir_back_input + dirname)\n\n if Add_Signal:\n root_file[self.sig_samplename] = ROOT.TFile(self.sig_filename)\n return root_file\n\n\n # get the corresponding root files for the data samples\n def get_data_root_files(self):\n list_dirs_data = os.listdir(self.dir_data_input)\n root_file_data = dict()\n\n for dirname in list_dirs_data:\n tmp_dataName1 = dirname.split(\"HAA4bAnalysis_\")[1]\n tmp_dataName2 = tmp_dataName1.replace(\".root\",\"\")\n root_file_data[tmp_dataName2] = ROOT.TFile(self.dir_data_input + dirname)\n return root_file_data\n\n\n#========================================================================================\n def get_best_combination(self, m1, m2, m3, m4):\n\n diff_m_12_34 = abs( (m1+m2).M() - (m3+m4).M() );\n diff_m_13_24 = abs( (m1+m3).M() - (m2+m4).M() );\n diff_m_14_23 = abs( (m1+m4).M() - (m2+m3).M() );\n\n diff_vector = [diff_m_12_34, diff_m_13_24, diff_m_14_23]\n diff_vector.sort()\n\n if diff_vector[0] == diff_m_12_34:\n return 1\n elif diff_vector[0] == diff_m_13_24:\n return 2\n elif diff_vector[0] == diff_m_14_23:\n return 3\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"test/Workflow_Handler.py","file_name":"Workflow_Handler.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"583025358","text":"from __future__ import absolute_import\nimport sys\nimport os\nimport seaborn as sns \nimport numpy as np\nimport scipy as sp\nsys.path.append('/home/drew/Documents/')\nsys.path.append('../')\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\nfrom ops.parameter_defaults import PaperDefaults\nfrom ops.single_hp_optim_yhist import optimize_model\nfrom ops import model_utils as utils\n\n\ndef run():\n defaults = PaperDefaults()\n\n # David's globals\n size = 51\n nr = 17\n npoints = 32//2\n ncontrasts = 5\n\n # experiment parameters\n # generate stimuli\n ##################\n im = []\n for k in range(nr):\n im_ = sp.zeros((size, size)) + sp.nan\n im_[size//2-k:size//2+k+1, size//2-k:size//2+k+1] = 0.5\n im.append(im_)\n im = sp.array(im)\n\n # generate populations\n ######################\n contrasts = sp.linspace(1., 0., ncontrasts, endpoint=False)[::-1]\n # contrasts = sp.logspace(-2, 0., ncontrasts)\n x = sp.array([utils.get_population(\n xim_, 'gaussian', npoints=npoints) for xim_ in im])\n ax = [c*x for c in contrasts]\n cx = np.concatenate(ax[:], axis=0)\n\n # Experimental data\n extra_vars = {}\n extra_vars['size'] = size\n extra_vars['npoints'] = npoints\n extra_vars['nr'] = nr\n extra_vars['stimsizes'] = 2*sp.arange(nr)+1\n extra_vars['ssn'] = defaults._DEFAULT_PARAMETERS['ssn']\n extra_vars['ssf'] = defaults._DEFAULT_PARAMETERS['ssf']\n extra_vars['hp_file'] = os.path.join(defaults._FIGURES, 'best_hps.npz')\n extra_vars['figure_name'] = 'size_tuning'\n extra_vars['return_var'] = 'O'\n extra_vars['contrasts'] = contrasts\n extra_vars['curvecols'] = sns.cubehelix_palette(ncontrasts)\n extra_vars['curvelabs'] = [\n 'Single-cell response at contrast %g' % (cst,) for cst in contrasts]\n optimize_model(cx, None, extra_vars, defaults)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"single_iteration_scripts/db_size_tuning.py","file_name":"db_size_tuning.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"239913027","text":"import heapq\n\nclass Solution:\n def kSmallestPairs(self, nums1, nums2, k):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n queue = []\n def push(i, j):\n if i < len(nums1) and j < len(nums2):\n heapq.heappush(queue, [nums1[i] + nums2[j], i, j])\n push(0, 0)\n pairs = []\n while queue and len(pairs) < k:\n _, i, j = heapq.heappop(queue)\n pairs.append([nums1[i], nums2[j]])\n push(i, j + 1)\n if j == 0:\n push(i + 1, 0)\n return pairs\n\nif __name__ == \"__main__\":\n sol = Solution()\n nums1 = [1,1,2]\n nums2 = [1,2,3]\n k = 10\n print(sol.kSmallestPairs(nums1, nums2, k))","sub_path":"373. Find K Pairs with Smallest Sums.py","file_name":"373. Find K Pairs with Smallest Sums.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"632680267","text":"import numpy as np\nimport time\nimport sys\nfrom matplotlib import rc\nrc('text', usetex=True)\nimport matplotlib.pyplot as plt\nimport math\nimport ctypes\nfrom scipy.optimize import curve_fit\nstart_time = time.time()\n\n# set up parameters \nphi0 = 0.1\nR_min = 5\nR_max = 500\ndata_root_path = \"/home/dc-bamb1/GRChombo/Analysis/data/Ylm_integration_data/\"\nnum = 800\nplot_interval = 10\nM = 1\nphi0 = 0.1\nlin_or_log = False\ncolours = ['r', 'b', 'g', 'm', 'c', 'y']\ncolours2 = [\"k\", \"m\", \"y\"]\nstyles = [\"-\", \"--\"]\n\nNphi=64\nNtheta=18\nTheta_max=1.0\n\nscale = \"\"\nif (lin_or_log):\n\tscale = \"linear\"\nelse:\n\tscale = \"log\"\n\nlog_y = True\n\nclass data_dir:\n\tdef __init__(self, num, l, m, a, mu, Al, nphi, ntheta, theta_max, l_, m_):\n\t\tself.num = num\n\t\tself.l = l\n\t\tself.m = m\n\t\tself.a = float(a)\n\t\tself.mu = float(mu)\n\t\tself.nphi = nphi\n\t\tself.ntheta = ntheta\n\t\tself.theta_max = float(theta_max)\n\t\tself.Al = Al\n\t\tself.l_ = l_\n\t\tself.m_ = m_\n\t\tself.name = \"run{:04d}_l{:d}_m{:d}_a{:s}_Al{:s}_mu{:s}_M1_IsoKerr\".format(num, l, m, a, Al, mu)\n\t#\n\tdef load_data(self, number):\n\t\tfile_name = self.name+\"_rho_Ylm_integral_{:s}_r_plus_to_{:d}_nphi{:d}_ntheta{:d}_theta_max{:.1f}_l={:d}_m={:d}.dat\".format(scale, R_max, self.nphi, self.ntheta, self.theta_max, self.l_, self.m_)\n\t\tdataset_path = data_root_path + file_name\n\t\tdata = np.genfromtxt(dataset_path, skip_header=1)\n\t\tprint(\"loaded \" + file_name)\n\t\tR = data[0,1:]\n\t\tr_plus = M*(1 + np.sqrt(1 - self.a**2))\n\t\tself.r = R*(1 + r_plus/(4*R))**2\n\t\trow = int(number/plot_interval)\n\t\tself.time = data[row,0]\n\t\trho = data[row,1:]\n\t\trho0 = 0.5*(phi0**2)*(self.mu)**2\n\t\tself.rho = rho/rho0\n\t\t\ndata_dirs = []\ndef add_data_dir(num, l, m, a, mu, l_, m_):\n\tx = data_dir(num, l, m, a, mu, \"0\", Nphi, Ntheta, Theta_max, l_, m_)\n\tdata_dirs.append(x)\n\n# choose datasets to compare\n\n\"\"\"run0002_l0_m0_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0005_l1_m1_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0006_l1_m1_a0.99_Al0_mu0.4_M1_IsoKerr\nrun0007_l2_m2_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0008_l4_m4_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0009_l1_m-1_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0010_l8_m8_a0.7_Al0_mu0.4_M1_IsoKerr\nrun0011_l1_m1_a0.7_Al0_mu2.0_M1_IsoKerr\nrun0012_l1_m1_a0.7_Al0_mu0.01_M1_IsoKerr\nrun0013_l2_m2_a0.7_Al0_mu0.8_M1_IsoKerr\nrun0014_l8_m8_a0.7_Al0_mu3.2_M1_IsoKerr\nrun0015_l1_m1_a0.7_Al0.5_mu0.4_M1_IsoKerr\nrun0016_l1_m-1_a0.99_Al0_mu0.4_M1_IsoKerr\nrun0017_l1_m1_a0.99_Al0.5_mu0.4_M1_IsoKerr\nrun0018_l1_m1_a0.99_Al0.25_mu0.4_M1_IsoKerr\"\"\"\n\n#add_data_dir(5, 1, 1, \"0.7\", \"0.4\", 2, 0)\n#add_data_dir(5, 1, 1, \"0.7\", \"0.4\", 2, 1)\nadd_data_dir(5, 1, 1, \"0.7\", \"0.4\", 2, 2)\n\ndef plot_graph():\n\t# plot setup\n\tax1 = plt.axes()\n\tfig = plt.gcf()\n\tfig.set_size_inches(3.8,3)\n\tfont_size = 10\n\ttitle_font_size = 10\n\tlabel_size = 10\n\tlegend_font_size = 10\n\trc('xtick',labelsize=font_size)\n\trc('ytick',labelsize=font_size)\n\t#\t\n\tfor i in range(0, len(data_dirs)):\n\t\tdd = data_dirs[i]\n\t\tdd.load_data(num)\n\t\tif (lin_or_log):\n\t\t\tx = dd.r/M\n\t\telse:\n\t \t\tx = np.log10(dd.r/M)\n\t\tif log_y:\n\t\t\ty = np.log10(dd.rho*(dd.r/M)**2)\n\t\telse:\n\t\t\ty = dd.rho*(dd.r/M)**2\n\t\tlabel_=\"$l=${:d} $m=${:d}\".format(dd.l_, dd.m_)\n\t\tax1.plot(x, y, colours[i] + \"-\", label=label_, linewidth=1)\n\tif log_y:\n\t\tax1.set_ylabel(\"$\\\\log_{10}((\\\\rho_{2m}/\\\\rho_0)(r^2/M^2))$\", fontsize=label_size)\n\telse:\n\t\tax1.set_ylim((0, 2000))\n\t\tax1.set_ylabel(\"$(\\\\rho_{2m}/\\\\rho_0)(r^2/M^2)$\", fontsize=label_size)\n\tif (lin_or_log):\n\t\txlabel_ = \"$r_{BL}/M$\"\n\telse:\n\t\txlabel_ = \"$\\\\log_{10}(r_{BL}/M)$\"\n\tplt.xlabel(xlabel_, fontsize=label_size)\n\t#a_max = np.max([float(a_str) for a_str in a_list])\n\t#r_plus_min = 1 + np.sqrt(1 - a_max**2)\n\t#print(\"r_plus_min = \", r_plus_min)\n\t#if (lin_or_log) :\n\t#\tplt.xlim((r_plus_min, 100))\n\t#else :\n\t#\tplt.xlim(left=np.log10(r_plus_min))\n\tax1.legend(loc=\"best\", fontsize=legend_font_size, labelspacing=0.1, handletextpad=0.2, borderpad=0.4)\n\tplt.xticks(fontsize=font_size)\n\tplt.yticks(fontsize=font_size)\n\tdd0 = data_dirs[0]\n\ttitle = \"$\\\\rho$ quadrupole profile $M=1,\\\\mu=0.4,\\\\chi=0.7,l=m=1$\" \n\tax1.set_title(title, fontsize=title_font_size)\n\tplt.tight_layout()\n\tif log_y:\n\t\t\tsave_name = \"/home/dc-bamb1/GRChombo/Analysis/plots/IsoKerr_rho_profile_{:s}_Rmax={:d}_n={:d}_quadrupole_log_y.png\".format(scale, R_max, num)\n\telse:\n\t\t\tsave_name = \"/home/dc-bamb1/GRChombo/Analysis/plots/IsoKerr_rho_profile_{:s}_Rmax={:d}_n={:d}_quadrupole.png\".format(scale, R_max, num)\n\tprint(\"saved \" + save_name)\n\tplt.savefig(save_name, transparent=False)\n\tplt.clf()\n\t\nplot_graph()\n","sub_path":"Analysis/scripts/old_scripts/plot_radial_profile_rho_Ylm_quadrupole.py","file_name":"plot_radial_profile_rho_Ylm_quadrupole.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"70591734","text":"from django.shortcuts import render\nfrom .models import *\n\n# Create your views here.\ndef orcamentos_lista(request):\n orcamentos = Orcamento.objects.all()\n return render(request, 'mp_orcamento/orcamentos.html', {'orcamentos': orcamentos})\n\n\ndef orcamentos_estatisticas(request):\n maior_custo = 0\n menor_custo = 999999999999\n orcamento_maior_custo = None\n orcamento_menor_custo = None\n orcamentos = Orcamento.objects.all()\n somatorio_custo_total = 0\n for orcamento in orcamentos:\n somatorio = 0\n for peca in Peca.objects.filter(orcamento=orcamento):\n somatorio += peca.custo_de_producao_ajustado()\n orcamento.custo_total = somatorio * 1.25\n somatorio_custo_total += orcamento.custo_total\n if orcamento.custo_total >= maior_custo:\n orcamento_maior_custo = orcamento\n maior_custo = orcamento.custo_total\n if orcamento.custo_total <= menor_custo:\n orcamento_menor_custo = orcamento\n menor_custo = orcamento.custo_total\n quantidade = Orcamento.objects.count() \n media_custo_total = somatorio_custo_total / quantidade\n return render(request, 'mp_orcamento/estatisticas.html', \n {'quantidade': quantidade, \n 'orcamento_maior_custo': orcamento_maior_custo,\n 'orcamento_menor_custo': orcamento_menor_custo,\n 'media_custo_total': media_custo_total\n })\n\n\ndef orcamentos_clientes(request):\n clientes = Cliente.objects.all().first()\n orcamentos = Orcamento.objects.filter(cliente=clientes)\n return render (request,'mp_orcamento/clientes.html',\n {'clientes': clientes,\n 'orcamentos': orcamentos\n })\n \n\ndef orcamentos_clientes_estatisticas(request):\n clientes = Cliente.objects.all()\n maior_custo = 0\n menor_custo = 999999999999\n orcamento_maior_custo = None\n orcamento_menor_custo = None\n nome_maior = None\n nome_menor = None\n for cliente in clientes:\n somatorio = 0\n for orcamento in Orcamento.objects.filter(cliente=cliente):\n somatorio += orcamento.custo_total()\n orcamento_total = somatorio\n if orcamento_total >= maior_custo:\n orcamento_maior_custo = orcamento_total\n nome_maior = cliente.nome\n maior_custo = orcamento_total\n if orcamento_total <= menor_custo:\n orcamento_menor_custo = orcamento_total\n nome_menor = cliente.nome\n menor_custo = orcamento_total\n quantidade = Cliente.objects.count()\n return render(request, 'mp_orcamento/clientes_estatisticas.html',\n {'quantidade': quantidade,\n 'orcamento_maior_custo': orcamento_maior_custo,\n 'orcamento_menor_custo': orcamento_menor_custo,\n 'nome_maior': nome_maior,\n 'nome_menor': nome_menor\n })\n\n \n","sub_path":"mp_orcamento/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"118147368","text":"from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom politician.factories import CongressServiceFactory\nfrom politician.services import PoliticianService\nfrom reports.utils import MONTHS\n\n\n@api_view()\ndef get_politician_total_expenses(request, politician_id):\n service = PoliticianService()\n politician = service.get_by_id(politician_id)\n\n total_expenses = 0\n congress_service = CongressServiceFactory(politician.role)\n for expense in congress_service.get_current_year_expenses(politician):\n total_expenses += expense[\"price\"]\n\n return Response({\n \"total\": total_expenses,\n \"total_formatted\": '{:,.2f}'.format(total_expenses)\n .replace(\",\", \"v\")\n .replace(\".\", \",\")\n .replace(\"v\", \".\")\n }, status.HTTP_200_OK)\n\n\n@api_view()\ndef get_politician_expenses_by_year(request, politician_id):\n service = PoliticianService()\n politician = service.get_by_id(politician_id)\n\n report = {\n \"xAxis\": {\n \"categories\": MONTHS\n },\n \"yAxis\": {\n \"min\": 0,\n \"title\": {\n \"text\": \"Gastos em R$\"\n }\n },\n\n \"series\": [{\n \"name\": \"Gastos\",\n \"color\": \"red\",\n \"data\": [0 for i in range(len(MONTHS))]\n }]\n }\n\n congress_service = CongressServiceFactory(politician.role)\n for expense in congress_service.get_current_year_expenses(politician):\n if not expense[\"date\"]:\n continue\n\n expense_month = int(expense[\"date\"].strftime(\"%m\")) - 1\n report[\"series\"][0][\"data\"][expense_month] += expense[\"price\"]\n\n return Response(report)\n\n\n@api_view()\ndef get_proposition_votes(request, proposition_at, proposition_id):\n service = CongressServiceFactory(proposition_at)\n votes, votes_by_party, votes_by_result = service.get_proposition_votes_by_id(\n proposition_id)\n\n reports = {\n \"votes\": votes,\n \"votes_by_party\": votes_by_party,\n \"votes_by_result\": votes_by_result\n }\n\n return Response(reports)\n","sub_path":"reports/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"465439537","text":"\r\nfrom math import *\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.cluster import DBSCAN\r\nfrom sklearn.cluster import SpectralClustering\r\nimport re\r\nfrom itertools import cycle\r\nimport urllib.request as ur\r\nimport requests\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\n\"\"\"\r\n特征工程\r\n1.特征提炼\r\n2.聚类+plot图\r\n\"\"\"\r\n\r\n'''\r\n根据 url 提炼出具体的host\r\n'''\r\ndef extractHost(full_link):\r\n regex = '((http|ftp|https|\\s)://)[a-zA-Z\\.0-9]+(?=\\/)'\r\n pattern = re.compile(regex)\r\n match = pattern.match(str(full_link))\r\n if match:\r\n # print(match.group())\r\n return match.group()\r\n return None\r\n\r\n\r\n\r\n'''\r\n根据 url 提炼出具体的请求目标,排除非内部请求,处理资源文件请求\r\n'''\r\ndef extractReqTarget(full_link):\r\n\r\n if \"qunar\" not in str(full_link):\r\n return None\r\n if \"qrt=\" in str(full_link):\r\n return full_link.partition('qrt=')[2]\r\n if \"html.ng\" in str(full_link):\r\n return 'qde'\r\n proto, rest = ur.splittype(full_link)\r\n res, rest = ur.splithost(rest)\r\n return None if not res else res\r\n\r\n\r\n'''\r\n输出 url:count\r\n'''\r\ndef exportUrls(reqUrl_df):\r\n targetFile = open('../data/urls.txt', \"a\",encoding='UTF-8')\r\n reqUrl_df_value_counts = reqUrl_df.value_counts()\r\n data_len = len(reqUrl_df_value_counts.index)\r\n for i in range(data_len):\r\n targetFile.write(str(reqUrl_df_value_counts.index[i])+' '+str(reqUrl_df_value_counts.values[i])+'\\r')\r\n targetFile.close()\r\n\r\n'''\r\n输出文件,上传datav,用于可视化\r\n'''\r\ndef exportHttpCodeNot200(df):\r\n train_data_dropnan_not200 = df[df['httpCode'] != 200 ]\r\n train_data_dropnan_not200['type'] = 1 ##用于指定气泡样式\r\n train_data_dropnan_not200[['lat','lng','httpCode','hf','type']].to_csv(\"../data/httpcodenot200.csv\",index=False)\r\n\r\n\r\ndef drawPlotForDBScan(df):\r\n x = np.array(df[['lat','lng']], dtype=np.float)\r\n per_city = 467.0994 #按边长为467.0994公里对中国切片\r\n # kms_per_radian = 6371.0088\r\n epsilon = 10/ per_city #一直memoryError,网上按比例缩放后可运行\r\n db = DBSCAN(eps=epsilon,min_samples=10, algorithm='ball_tree', metric='haversine').fit(np.radians(x))\r\n labels = db.labels_\r\n unique_labels = set(labels)\r\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\r\n colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')\r\n markers = []\r\n for i in range(n_clusters_):\r\n markers.append('o')\r\n\r\n for k , col , mar in zip(unique_labels , colors , markers):\r\n if k == -1:\r\n col = 'r'\r\n members = (labels == k )\r\n print( x[members, 0],x[members,1])\r\n plt.plot( x[members, 0] , x[members,1] , 'w', markerfacecolor=col, marker='.',markersize=8)\r\n plt.title(u'number of clusters: %d' % n_clusters_)\r\n plt.xlabel('lat')\r\n plt.ylabel('lng')\r\n plt.grid()\r\n plt.show()\r\n\r\n\r\ndef locatebyLatLon(lat, lng, pois=0):\r\n '''\r\n 根据经纬度确定地址\r\n '''\r\n try:\r\n items = {'location': str(lat) + ',' + str(lng), 'ak': 'A9f77664caa0b87520c3708a6750bbdb', 'output': 'json'}\r\n if pois:\r\n items['pois'] = 1\r\n r = requests.get('http://api.map.baidu.com/geocoder/v2/', params=items)\r\n dictResult = r.json()\r\n return dictResult['result'] if not dictResult['status'] else None\r\n except Exception as e:\r\n print(str(e))\r\n return None\r\n\r\n\r\ndef toDateTime(ds):\r\n if '+' not in str(ds):\r\n return None\r\n clean_s = str(ds).split('+')[0]\r\n return pd.to_datetime(clean_s)\r\n\r\ndef getClusterId(dfdd,x):\r\n\r\n for loc_value,cluster_id_value in dfdd[['loc','cluster_id']].values:\r\n if x == loc_value:\r\n return cluster_id_value\r\n return -1\r\n\r\n\r\ndef spectralCluster(df):\r\n df_dropduplicates = df[['lat', 'lng','loc']].drop_duplicates()\r\n x = np.array(df_dropduplicates[['lat', 'lng']], dtype=np.float)\r\n sc = SpectralClustering(n_clusters=30, eigen_solver='arpack',\r\n affinity=\"nearest_neighbors\").fit(np.radians(x))\r\n labels = sc.labels_\r\n # print(labels)\r\n df_dropduplicates['cluster_id'] = labels\r\n df['cluster_id'] = df['loc'].apply(lambda x :getClusterId(df_dropduplicates,x))\r\n print(df[['loc','cluster_id']].values)\r\n\r\n newdf = df.groupby(\"cluster_id\").mean()\r\n cluster_dict = {}\r\n for i, j in newdf.iterrows():\r\n ret = locatebyLatLon(j['lng'], j['lat'])\r\n if ret:\r\n city = ret['addressComponent']['province'] + \",\" + ret['addressComponent']['city']\r\n cluster_dict[i] = city\r\n else:\r\n cluster_dict[i] = None\r\n print (cluster_dict)\r\n return df['cluster_id'].replace(cluster_dict)\r\n\r\n\r\n\r\nif __name__== \"__main__\":\r\n global defaultTrainData\r\n # try:\r\n # for i in range(3,25):\r\n\r\n # url = \"../data/data\"+str(i)+\".txt\" ##数据地址\r\n # print(url)\r\n # defaultTrainData = pd.read_csv(url,sep='$') ##读取文件\r\n # '''\r\n # 占时提取这些特征进行处理,后续可以自己加上, 将none值去除,以后可考虑进行填充\r\n # '''\r\n # train_data_dropnan = defaultTrainData[['loc','httpCode','reqUrl','reqTime','mno','resSize','netType','uid','pid','hf','X-Date']]\r\n\r\n # train_data_dropnan['httpCode'] = train_data_dropnan['httpCode'].fillna(200)\r\n\r\n # train_data_dropnan['hf'] = train_data_dropnan['hf'].apply(lambda x: None if str(x) else \"service_error\")\r\n # train_data_dropnan['hf'] = train_data_dropnan['hf'].dropna()\r\n\r\n\r\n # ##可能反了,但不影响具体训练\r\n # ##lat提取\r\n # train_data_dropnan['lat'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[0]) if ',' in str(x) else 0)\r\n # ##lng提取\r\n # train_data_dropnan['lng'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[1]) if ',' in str(x) else 0)\r\n # ##host提取\r\n # train_data_dropnan['host'] = train_data_dropnan['reqUrl'].apply(lambda x:extractHost(str(x)))\r\n # ##reqTarget提取\r\n # train_data_dropnan['reqTarget'] = train_data_dropnan['reqUrl'].apply(lambda x:extractReqTarget(str(x)))\r\n\r\n # train_data_dropnan['X-Date'] = train_data_dropnan['X-Date'].apply(lambda x: toDateTime(x))\r\n\r\n # train_data_dropnan['minute'] = train_data_dropnan['X-Date'].apply(lambda x: x.minute)\r\n\r\n # train_data_dropnan.sort(['X-Date'],ascending=True)\r\n\r\n # train_data_dropnan['city'] = None\r\n # for j in range(60):\r\n # print(j)\r\n # train_data_dropnan_permin = train_data_dropnan[train_data_dropnan['minute'] == j];\r\n # loc_data_permin = train_data_dropnan_permin[['loc', 'minute']].dropna()\r\n # loc_data_permin['lat'] = loc_data_permin['loc'].apply(lambda x: float(str(x).split(',')[0]))\r\n # ##lng提取\r\n # loc_data_permin['lng'] = loc_data_permin['loc'].apply(lambda x: float(str(x).split(',')[1]))\r\n # # for k in range(0, loc_data.size, 2000):\r\n # replace_item = spectralCluster(loc_data_permin)\r\n # train_data_dropnan_permin['city'] = replace_item\r\n # print(train_data_dropnan_permin['X-Date'].values)\r\n # file_name = train_data_dropnan_permin['X-Date'].iloc[0].strftime('%y-%m-%d-%H-%M')\r\n # print(file_name)\r\n # train_data_dropnan_permin.to_csv(\"../input/\"+str(file_name)+\".csv\",index=False,sep='$',encoding=\"utf-8\")\r\n\r\n # defaultTrainData = None\r\n # except Exception as e:\r\n # print(str(e)) \r\n url = \"../data/data0.txt\" ##数据地址\r\n print(url)\r\n defaultTrainData = pd.read_csv(url,sep='$') ##读取文件\r\n '''\r\n 占时提取这些特征进行处理,后续可以自己加上, 将none值去除,以后可考虑进行填充\r\n '''\r\n train_data_dropnan = defaultTrainData[['loc','httpCode','reqUrl','reqTime','mno','resSize','netType','uid','pid','hf','X-Date']]\r\n\r\n train_data_dropnan['httpCode'] = train_data_dropnan['httpCode'].fillna(200)\r\n\r\n train_data_dropnan['hf'] = train_data_dropnan['hf'].apply(lambda x: None if str(x) else \"service_error\")\r\n train_data_dropnan['hf'] = train_data_dropnan['hf'].dropna()\r\n\r\n\r\n ##可能反了,但不影响具体训练\r\n ##lat提取\r\n train_data_dropnan['lat'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[0]) if ',' in str(x) else 0)\r\n ##lng提取\r\n train_data_dropnan['lng'] = train_data_dropnan['loc'].apply(lambda x: float(str(x).split(',')[1]) if ',' in str(x) else 0)\r\n # ##host提取\r\n # train_data_dropnan['host'] = train_data_dropnan['reqUrl'].apply(lambda x:extractHost(str(x)))\r\n # ##reqTarget提取\r\n # train_data_dropnan['reqTarget'] = train_data_dropnan['reqUrl'].apply(lambda x:extractReqTarget(str(x)))\r\n\r\n # train_data_dropnan['X-Date'] = train_data_dropnan['X-Date'].apply(lambda x: toDateTime(x))\r\n\r\n # train_data_dropnan['minute'] = train_data_dropnan['X-Date'].apply(lambda x: x.minute)\r\n drawPlotForDBScan(train_data_dropnan)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"monitor-script/feature_analyze.py","file_name":"feature_analyze.py","file_ext":"py","file_size_in_byte":9352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"46765984","text":"import os\nfrom flask import Flask, request, jsonify\n\nUPLOAD_FOLDER = '/home/pi/context'\n\napp = Flask(__name__)\n\ndef save_reg(regs):\n\twith open(os.path.join(UPLOAD_FOLDER, \"context.txt\"), \"w\") as f:\n\t\tfor reg in regs:\n\t\t\tf.write(str(reg) + '\\n')\n\ndef save_code(code):\n\twith open(os.path.join(UPLOAD_FOLDER, \"instruction.s\"), \"w\") as f:\n\t\tf.write(code)\n\t\n\n@app.route('/', methods=['POST'])\ndef upload_files():\n\tdata = request.get_json()\n\t\n\tregisters = data['registers']\n\tcode = data['code']\n\n\tprint(request)\n\n\tif registers:\n\t\tsave_reg(registers)\n\telse:\n\t\treturn \"You should send context\", 400\n\n\tif code:\n\t\tsave_code(code)\n\telse:\n\t\treturn \"You should send instruction\", 400\n\n\tos.system(\"python3 readContext.py context/instruction.s context/context.txt\")\n\tos.system(\"gcc -o test test.s -mfpu=neon\")\n\n\tos.system(\"./test > response.txt\")\n\n\tout_regs = []\n\n\twith open(\"response.txt\") as f:\n\t\tfor line in f:\n\t\t\tout_regs.append(int(line))\n\n\tf.close()\n\n\tos.system(\"rm -rf test.s\")\n\tos.system(\"rm -rf test\")\n\tos.system(\"rm -rf response.txt\")\n\n\treturn jsonify({\"registers\": out_regs}), 200\n\napp.run(host='0.0.0.0', port=8080)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"497298631","text":"from PIL import Image\nimport numpy as np\n\nimage = Image.open(\"angelBW.jpg\")\n\npixels = np.asarray(image, dtype=np.float32)\na = pixels[:,:,0]\nx, y = a.shape\nprint(a.shape)\nprint(x, y)\nnewImage = []\ngx = 0\ngy = 0\ng = 0\ni = 0\nj= 0\nt = 50\nmatriz = []\nfor i in range(x-3):\n temp_array = []\n for j in range(y-3):\n temp = a[i:(i+3), j:(j+3)]\n gx = temp[1,1] - temp[0,0]\n gy = temp[1,0] - temp[0,1]\n g = (gx**2 + gy**2)**(0.5)\n if g > t:\n temp_array.append(255)\n else:\n temp_array.append(0)\n matriz.append(temp_array)\n\nmatriz = np.asarray(matriz, dtype=np.uint8)\nImage.fromarray(matriz.astype(np.uint8)).save(\"holaR.jpg\")\nimage.close()\n","sub_path":"procesamientoDeImagenes/mascaras/robert.py","file_name":"robert.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"624854077","text":"import numpy as np\n\nR = 2.5\nA = 4*R/70\nN = 15\n\nphi = np.arange(0, 2 * np.pi, 0.01)\nrho = R + A * np.sin(N * phi)\n\nsPnts = []\nfor p, r in zip(phi, rho):\n x = 2 * r * np.cos(p)\n y = r * np.sin(p)\n sPnts += [(x, y, 0)]\n\ns = cq.Workplane(\"XY\").moveTo(sPnts[0][0], sPnts[0][1])\nr = s.spline(sPnts[1:], includeCurrent = True).close()\nresult = r.workplane(offset = 10.0).ellipse(2.5, 1.25).loft(combine=True)","sub_path":"lattice_scripts/wavy_circle.py","file_name":"wavy_circle.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"636937917","text":"#Random으로 오늘의 점심메뉴를 추천해주는 프로그램\nimport random\n\nmenu = ['새마을식당', '초원삼겹살', '멀캠20층', '홍콩반점', '순남시래기']\n\n#dictionary\nphone_book = {\n '새마을식당':'010-2536-2563',\n '초원삼겹살':'010-5987-8359',\n '멀캠20층':'010-3134-1347',\n '홍콩반점':'010-2361-1234',\n '순남시래기':'010-1236-3457'\n} #json파일 형식과 같아보이는데 같은방식일 것 같다\nprint(phone_book['새마을식당'])\nlunch = random.choice(menu);\nprint(lunch);\n\n#해당 식당의 전화번호를 같이 출력\nprint(phone_book[lunch])","sub_path":"VR교육과정특강Python/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"136809164","text":"# By Ben Curnow\n# www.github.com/bencurnow\n# A pool ladder\n\n\nimport datetime\n\n\nladder = {}\nn = 3\ndate = datetime.datetime.now().date()\ntickcross = ['\\u2713', '\\u2717']\n\n\n# Converts a list to a string\ndef liststring(l):\n string = ''\n for i in l:\n string += str(i) + ' '\n return string[:-1]\n\n\n# Prints the ladder to the console\ndef prettyprint(dic):\n for i in dic:\n print(i, dic[i][0], tickcross[int(dic[i][2])])\n\n\n# Opens the ladder.txt file and stores in ladderlist\nwith open(\"ladder.txt\") as file:\n ladderlist = [i[:-1].split() for i in file]\n\n\n# Opens the challenge.txt file and stores in challenges\nwith open(\"challenge.txt\") as file:\n challenges = [(i.split()[0], i.split()[1], i.split()[2]) for i in file]\n\n\n# Opens the challengehist.txt file and stores in challengehist\nwith open(\"challengehist.txt\") as file:\n challengehist = [i for i in file]\n\n\n# Parses data from ladder list to the ladder dictionary\nfor i in ladderlist:\n ladder[int(i[0])] = []\n ladder[int(i[0])].append(liststring([str(k) for k in i[n:]]))\n for k in range(1, n):\n ladder[int(i[0])].append(i[k])\n\n\n# Hunts for a player in the ladder\ndef hunter(player):\n for i in range(1, len(ladder)):\n if ladder[i][0] == player:\n return i\n elif ladder[i][1] == player:\n return i\n\n\n# Swaps 2 people in the ladder\ndef swapentries(p1, p2):\n temp1, temp2 = ladder[p1], ladder[p2]\n ladder[p1], ladder[p2] = temp2, temp1\n\n\n# Promotes a player p1 to position p2\ndef promote(p1, p2):\n for i in range(p1 - p2):\n swapentries(p1 - i, p1 - i - 1)\n\n\n# Removes a challenge from the list\ndef remchallenge(player):\n print(challenges)\n for i in challenges:\n if i[0] == player or i[1] == player:\n ladder[hunter(i[0])][2], ladder[hunter(i[1])][2] = 0, 0\n challenges.remove(i)\n return True\n return False\n\n\n# Allows a result to be placed in the challenge history\ndef resulthandler(p1, result):\n for i in challenges:\n if i[0] == p1 or i[1] == p1:\n challengehist.append(str(i[0]) + ' ' + str(i[1]) + ' ' + str(i[2]) + ' ' + result + '\\n')\n remchallenge(p1)\n\n\n# Checks the challenge keys to update current challenges\ndef updatechallenges():\n for i in challenges:\n ladder[hunter(i[0])][2], ladder[hunter(i[1])][2] = 1, 1\n chaldate = datetime.datetime(int(i[2][:4]), int(i[2][5:7]), int(i[2][8:]))\n if (datetime.datetime.now() - chaldate).days > 3:\n if hunter(i[0]) < hunter(i[1]):\n promote(hunter(i[1]), hunter(i[0]))\n else:\n promote(hunter(i[0]), hunter(i[1]))\n resulthandler(i[0], 'Auto-Resign')\nupdatechallenges()\n\n\n# Allows a player to challenge\ndef challenge(p1, p2):\n if p1 - 3 > p2 or p1 <= p2:\n return False\n elif ladder[p1][2] == 1 or ladder[p2][2] == 1:\n return False\n else:\n challenges.append((ladder[p1][1], ladder[p2][1], str(date)))\n updatechallenges()\n return True\n\n\n# Functionality for challenging\ndef challengehandler(p1, p2):\n if challenge(p1, p2):\n print(\"Challenge successful\")\n else:\n print(\"Challenge unsuccessful\")\n\n\nprettyprint(ladder)\n\n\n# Writes the new ladder to the text document for next use\nwith open(\"newladder.txt\", 'w') as f:\n for i in ladder:\n f.write(str(i) + ' ' + str(ladder[i][1]) + ' ' + str(ladder[i][2]) + ' ' + str(ladder[i][0]) + '\\n')\n\n# Writes the challenges to the text document for next use\nwith open(\"challenge.txt\", 'w') as f:\n for i in challenges:\n f.write(str(i[0]) + ' ' + str(i[1]) + ' ' + str(i[2]) + '\\n')\n\n# Writes the challenge history to the text document for next use\nwith open(\"challengehist.txt\", 'w') as f:\n for i in challengehist:\n f.write(i)\n\n\n","sub_path":"ladder.py","file_name":"ladder.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"442446645","text":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python import debug as tf_debug\nfrom tqdm import *\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numbers\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom Visual import *\nfrom Utils import *\n\nclass UnitAutoencoder:\n \"\"\"\n A single autoencoder which can be either an ordinary or a denoising unit. Denoising autoencoder can be \n specified with Gaussian noises or dropout on the inputs.\n \"\"\"\n def __init__(self,\n name,\n n_inputs,\n n_neurons,\n noise_stddev = None,\n input_dropout_rate = None,\n hidden_dropout_rate = None,\n hidden_activation = tf.nn.softmax,\n output_activation = None,\n n_observable_hidden_neurons = 0,\n regularizer = tf.contrib.layers.l2_regularizer(0.01),\n initializer = tf.contrib.layers.variance_scaling_initializer(), # He initialization\n optimizer = tf.train.AdamOptimizer(0.001),\n tf_log_dir = \"../tf_logs\"):\n \"\"\"\n Ctor\n \n Arguments:\n - name: name of the unit\n - n_inputs: number of inputs; also the number of neurons in the output layer\n - n_neurons: number of neurons in the hidden layer\n - noise_stddev: standard deviation of the Gaussian noise; not used if None\n - dropout_rate: if specified a Dropout layer will be added after the input layer; not used if None\n - regularizer: kernel regularizers for hidden and output layers\n\n Return: None\n \"\"\"\n self.name = name\n self.n_inputs = n_inputs\n self.n_neurons = n_neurons\n self.noise_stddev = noise_stddev\n self.input_dropout_rate = input_dropout_rate\n self.hidden_dropout_rate = hidden_dropout_rate\n self.hidden_activation = hidden_activation\n self.output_activation = output_activation\n self.regularizer = regularizer\n self.initializer = initializer\n self.n_observable_hidden_neurons = 0\n if (n_observable_hidden_neurons > 0):\n if isinstance(n_observable_hidden_neurons, numbers.Integral):\n self.n_observable_hidden_neurons = min(n_observable_hidden_neurons, self.n_neurons)\n elif isinstance(n_observable_hidden_neurons, numbers.Real):\n assert(0.0 <= n_observable_hidden_neurons <= 1.0), \"Invalid ratio\"\n self.n_observable_hidden_neurons = int(n_observable_hidden_neurons * self.n_neurons)\n else:\n raise ValueError(\"Invalid type\")\n self.graph = tf.Graph()\n\n with self.graph.as_default():\n self.X = tf.placeholder(tf.float32, shape=[None, n_inputs], name=\"X\")\n self.training = tf.placeholder_with_default(False, shape=(), name='training')\n if (self.noise_stddev is not None):\n X_noisy = tf.cond(self.training,\n lambda: self.X + tf.random_normal(tf.shape(self.X), stddev = self.noise_stddev),\n lambda: self.X)\n elif (self.input_dropout_rate is not None):\n X_noisy = tf.layers.dropout(self.X, self.input_dropout_rate, training=self.training)\n else:\n X_noisy = self.X\n dense_hidden = tf.layers.dense(X_noisy, n_neurons, activation=hidden_activation, kernel_regularizer = regularizer, name=\"{}_hidden\".format(self.name))\n if self.hidden_dropout_rate is None:\n self.hidden = dense_hidden\n else:\n self.hidden = tf.layers.dropout(dense_hidden, self.hidden_dropout_rate, training=self.training)\n self.outputs = tf.layers.dense(self.hidden, n_inputs, activation=output_activation, kernel_regularizer = regularizer, name=\"{}_outputs\".format(self.name))\n self.reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n self.reconstruction_loss = tf.reduce_mean(tf.square(self.outputs - self.X))\n self.loss = tf.add_n([self.reconstruction_loss] + self.reg_losses)\n self.training_op = optimizer.minimize(self.loss)\n self.init = tf.global_variables_initializer()\n self.saver = tf.train.Saver()\n\n loss_str = \"Reconstruction_and_regularizer loss\" if regularizer else \"Reconstruction_loss\"\n self.loss_summary = tf.summary.scalar(loss_str, self.loss)\n # Ops to observe neurons\n if (self.n_observable_hidden_neurons > 0):\n trainable_vars = dict([(var.name, var) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n hidden_weights = trainable_vars[\"{}_hidden/kernel:0\".format(self.name)]\n assert(hidden_weights.shape == (n_inputs, n_neurons)), \"Invalid hidden weight shape\"\n hidden_biases = trainable_vars[\"{}_hidden/bias:0\".format(self.name)]\n if self.n_observable_hidden_neurons == self.n_neurons:\n # Optimization for corner case to avoid permutation\n neuron_indices = np.arange(self.n_neurons)\n else:\n neuron_indices = list(np.random.permutation(np.arange(n_neurons))[:self.n_observable_hidden_neurons])\n for neuron_idx in neuron_indices:\n self._variable_summaries(hidden_weights[:, neuron_idx], \"weights_hidden_neuron_{}\".format(neuron_idx))\n self._variable_summaries(hidden_biases[neuron_idx], \"bias_hidden_neuron_{}\".format(neuron_idx))\n self._variable_summaries(self.hidden[:, neuron_idx], \"activation_hidden_neuron_{}\".format(neuron_idx))\n \n self.summary = tf.summary.merge_all()\n tf_log_dir = \"{}/{}_run-{}\".format(tf_log_dir, self.name, timestr())\n self.train_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"train\"), self.graph)\n self.valid_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"valid\"), self.graph)\n \n # Dictionary of trainable parameters: key = variable name, values are their values (after training or\n # restored from a model)\n self.params = None\n\n # The trainable params with initial values (before traininig or restoration)\n self.initial_params = None\n\n # Stop file: if this file exists, the training will stop\n self.stop_file_path = os.path.join(tf_log_dir, \"stop\")\n \n def _variable_summaries(self, var, tag):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope(tag):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var) \n\n def save_untrained_model(self, model_path, seed = 42):\n with tf.Session(graph=self.graph) as sess:\n tf.set_random_seed(seed)\n self.init.run()\n self.initial_params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n self.saver.save(sess, model_path)\n \n def fit(self, X_train, X_valid, n_epochs, model_path, save_best_only = True, batch_size = 256, checkpoint_steps = 100, seed = 42, tfdebug = False):\n \"\"\"\n Train the unit autoencoder against a training set\n\n Params:\n - X_train: training set of shape (n_samples, n_features)\n - X_valid: validation set\n - n_epochs: number of epochs to train\n - batch_size: batch size\n - checkpoint_steps: number of steps to record checkpoint and logs\n - seed: random seed for tf\n - model_path: model full path file to be saved\n\n \"\"\"\n assert(self.X.shape[1] == X_train.shape[1]), \"Invalid input shape\"\n with tf.Session(graph=self.graph) as sess:\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if batch_size is None:\n batch_size = len(X_train)\n tf.set_random_seed(seed)\n self.init.run()\n self.initial_params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n best_loss_on_valid_set = 100000\n model_step = -1\n stop = False\n for epoch in tqdm(range(n_epochs)):\n X_train_indices = np.random.permutation(len(X_train))\n n_batches = len(X_train) // batch_size\n start_idx = 0\n for batch_idx in range(n_batches):\n indices = X_train_indices[start_idx : start_idx + batch_size]\n X_batch = X_train[indices]\n sess.run(self.training_op, feed_dict={self.X: X_batch, self.training: True}) \n step = epoch * n_batches + batch_idx\n if step % checkpoint_steps == 0:\n train_summary = sess.run(self.summary, feed_dict={self.X: X_batch})\n self.train_file_writer.add_summary(train_summary, step)\n loss_on_valid_set, loss_summary_on_valid_set = sess.run([self.loss, self.loss_summary], feed_dict={self.X: X_valid})\n self.valid_file_writer.add_summary(loss_summary_on_valid_set, step)\n model_to_save = (not save_best_only) or (loss_on_valid_set < best_loss_on_valid_set)\n if loss_on_valid_set < best_loss_on_valid_set:\n best_loss_on_valid_set = loss_on_valid_set\n if model_to_save:\n self.saver.save(sess, model_path)\n model_step = step\n # Check if stop signal exists\n if os.path.exists(self.stop_file_path):\n stop = True\n start_idx += batch_size\n if stop:\n print(\"Stopping command detected: {}\".format(self.stop_file_path))\n break\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n self.train_file_writer.close()\n self.valid_file_writer.close()\n assert(model_step >= 0), \"Invalid model step\"\n all_steps = n_epochs * n_batches\n return model_step, all_steps\n \n def hidden_weights(self, file_path = None):\n assert(self.params is not None), \"Invalid self.params\"\n w = self.params[\"{}_hidden/kernel:0\".format(self.name)]\n if file_path is not None:\n W = np.array(w)\n columns = [\"neuron_{}\".format(idx) for idx in range(W.shape[1])]\n df = pd.DataFrame(data=W, columns=columns)\n df.to_csv(file_path)\n return w\n\n def hidden_biases(self, file_path = None):\n assert(self.params is not None), \"Invalid self.params\"\n w = self.params[\"{}_hidden/bias:0\".format(self.name)]\n if file_path is not None:\n W = np.array(w)\n columns = [\"neuron_{}\".format(idx) for idx in range(W.shape[1])]\n df = pd.DataFrame(data=W, columns=columns)\n df.to_csv(file_path)\n return w\n \n def output_weights(self):\n assert(self.params is not None), \"Invalid self.params\"\n return self.params[\"{}_output/kernel:0\".format(self.name)]\n\n def output_biases(self):\n assert(self.params is not None), \"Invalid self.params\"\n return self.params[\"{}_output/bias:0\".format(self.name)]\n \n def restore(self, model_path):\n if self.params is not None:\n print(\">> Warning: self.params not empty and will be replaced\")\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n\n def eval(self, X, varlist):\n assert(self.params), \"Invalid self.params\"\n with tf.Session(graph=self.graph) as sess:\n varmap = {\"loss\": self.loss,\n \"reconstruction_loss\": self.reconstruction_loss,\n \"hidden_outputs\": self.hidden,\n \"outputs\": self.outputs}\n vars_to_eval = []\n for var in varlist:\n # The order of var in the list needs to be kept, thus this for-loop\n if var == \"loss\":\n vars_to_eval += [self.loss]\n elif var == \"reconstruction_loss\":\n vars_to_eval += [self.reconstruction_loss]\n elif var == \"hidden_outputs\":\n vars_to_eval += [self.hidden]\n elif var == \"outputs\":\n vars_to_eval += [self.outputs]\n else:\n raise ValueError(\"Unrecognized variable {} to evaluate\".format(var))\n return sess.run(vars_to_eval, feed_dict={self.X: X})\n \n def restore_and_eval(self, X, model_path, varlist, tfdebug = False):\n \"\"\"\n Restore model's params and evaluate variables\n\n Params:\n - model_path: full path to the model file\n - varlist: list of variables to evaluate. Valid values: \"loss\", \"reconstruction_loss\", \"hidden_outputs\", \"outputs\"\n\n Return: a list of evaluated variables\n \"\"\"\n assert(self.graph), \"Invalid graph\"\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n varmap = {\"loss\": self.loss,\n \"reconstruction_loss\": self.reconstruction_loss,\n \"hidden_outputs\": self.hidden,\n \"outputs\": self.outputs}\n vars_to_eval = []\n for var in varlist:\n # The order of var in the list needs to be kept, thus this for-loop\n if var == \"loss\":\n vars_to_eval += [self.loss]\n elif var == \"reconstruction_loss\":\n vars_to_eval += [self.reconstruction_loss]\n elif var == \"hidden_outputs\":\n vars_to_eval += [self.hidden]\n elif var == \"outputs\":\n vars_to_eval += [self.outputs]\n return sess.run(vars_to_eval, feed_dict={self.X: X})\n\n##################################################################################\n##\n## StackAutoencoders class\n##\n##################################################################################\nclass StackedAutoencoders:\n def __init__(self,\n name,\n cache_dir = \"../cache\",\n tf_log_dir = \"../tf_logs\"):\n self.name = name\n self.stacked_units = []\n self.graph = None\n self.initial_params = None\n self.params = None\n self.cache_dir = cache_dir\n self.tf_log_dir = tf_log_dir\n\n self.X = None\n self.training = None\n self.loss = None\n self.hidden = [] # outputs of all hidden layers\n self.outputs = None # the final output layer\n self.encoders = []\n self.decoders = []\n self.training_op = None\n self.saver = None\n self.loss_summary = None\n self.summary = None\n self.train_file_writer = None \n self.stop_file_path = os.path.join(cache_dir, \"stop\")\n \n def _add_hidden_layer(self, input_tensor, unit, layer_name,\n regularizer,\n input_dropout_rate,\n hidden_dropout_rate):\n assert(unit.params), \"Invalid unit.params\"\n with tf.name_scope(layer_name):\n input_drop = input_tensor if input_dropout_rate is None else tf.layers.dropout(input_tensor, rate=input_dropout_rate, training=self.training)\n weights = tf.Variable(unit.hidden_weights(), name = \"weights\")\n assert(weights.shape == (unit.n_inputs, unit.n_neurons)), \"Wrong assumption about weight's shape\"\n biases = tf.Variable(unit.hidden_biases(), name = \"biases\")\n assert(biases.shape == (unit.n_neurons,)), \"Wrong assumption about bias's shape\"\n pre_activations = tf.matmul(input_drop, weights) + biases\n if unit.hidden_activation is not None:\n hidden_outputs = unit.hidden_activation(pre_activations, name = \"hidden_outputs\")\n else:\n hidden_outputs = pre_activations\n hidden_drop = hidden_outputs if hidden_dropout_rate is None else tf.layers.dropout(hidden_outputs, rate=hidden_dropout_rate, training=self.training)\n reg_loss = regularizer(weights) if regularizer else None\n return hidden_drop, reg_loss\n\n def _add_output_layer(self, input_tensor, unit, layer_name,\n regularizer,\n input_dropout_rate,\n output_dropout_rate):\n assert(unit.params), \"Invalid unit.params\"\n with tf.name_scope(layer_name):\n input_drop = input_tensor if input_dropout_rate is None else tf.layers.dropout(input_tensor, rate=input_dropout_rate, training=self.training)\n weights = tf.Variable(unit.output_weights(), name = \"weights\")\n assert(weights.shape == (unit.n_inputs, unit.n_neurons)), \"Wrong assumption about weight's shape\"\n biases = tf.Variable(unit.output_biases(), name = \"biases\")\n assert(biases.shape == (unit.n_neurons,)), \"Wrong assumption about bias's shape\"\n pre_activations = tf.matmul(input_drop, weights) + biases\n if unit.output_activation is not None:\n outputs = unit.output_activation(pre_activations, name = \"hidden_outputs\")\n else:\n outputs = pre_activations\n outputs_drop = outputs if output_dropout_rate is None else tf.layers.dropout(outputs, rate=output_dropout_rate, training=self.training)\n reg_loss = regularizer(weights) if regularizer else None\n return outputs_drop, reg_loss\n \n def stack_encoder(self, unit, layer_name,\n regularizer = None,\n input_dropout_rate = 0,\n hidden_dropout_rate = 0):\n self.graph = tf.Graph() if self.graph is None else self.graph\n with self.graph.as_default():\n intput_tensor = None\n if not self.hidden: # empty hidden layers\n self.X = tf.placeholder(tf.float32, shape=(None, unit.n_inputs), name=\"X\")\n self.y = tf.placeholder(tf.int64, shape=(None), name=\"y\")\n self.training = tf.placeholder_with_default(False, shape=(), name=\"training\")\n input_tensor = self.X\n else:\n input_tensor = self.hidden[-1]\n hidden, reg_loss = self._add_hidden_layer(input_tensor, unit, layer_name,\n regularizer, input_dropout_rate, hidden_dropout_rate)\n self.hidden += [hidden]\n self.encoders += [hidden]\n self.stacked_units += [unit]\n if reg_loss is not None:\n self.loss = tf.add_n([self.loss, reg_loss]) if self.loss is not None else reg_loss\n\n def stack_decoder(self, unit, layer_name,\n is_reconstruction_layer = False,\n regularizer = None,\n input_dropout_rate = 0,\n output_dropout_rate = 0):\n self.graph = tf.Graph() if self.graph is None else self.graph\n with self.graph.as_default():\n assert(self.hidden), \"Empty encoder layers\"\n input_tensor = self.hidden[-1]\n outputs, reg_loss = self._add_output_layer(input_tensor, unit, layer_name,\n regularizer, input_dropout_rate, output_dropout_rate)\n if reg_loss is not None:\n self.loss = tf.add_n([self.loss, reg_loss]) if self.loss is not None else reg_loss\n if is_reconstruction_layer:\n self.outputs = outputs\n reconstruction_loss = tf.reduce_mean(tf.square(self.outputs - self.X))\n self.loss = tf.add_n([self.loss, reconstruction_loss]) if self.loss is not None else reconstruction_loss\n else:\n self.hidden += [outputs]\n self.decoders += [outputs]\n \n def stack_softmax_output_layer(self,\n layer_name,\n kernel_regularizer = None,\n kernel_initializer = tf.contrib.layers.variance_scaling_initializer(),\n bias_initializer = tf.zeros_initializer()):\n assert(self.hidden), \"Empty hidden layers\"\n assert(self.graph), \"Empty graph\"\n with self.graph.as_default():\n with tf.variable_scope(layer_name):\n weights = tf.get_variable(name=\"weights\",\n shape=(self.hidden[-1].shape[1], self.X.shape[1]),\n initializer=kernel_initializer)\n biases = tf.get_variable(name=\"biases\",\n shape=(self.X.shape[1], ),\n initializer=bias_initializer)\n self.outputs = tf.matmul(self.hidden[-1], weights) + biases\n with tf.variable_scope(\"loss\"):\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.y, logits=self.outputs)\n entropy_loss = tf.reduce_mean(cross_entropy, name=\"entropy_loss\")\n self.loss = tf.add_n([self.loss, entropy_loss]) if self.loss is not None else entropy_loss\n self.loss = tf.add_n([self.loss, kernel_regularizer(weights)]) if kernel_regularizer is not None else self.loss\n \n def finalize(self, optimizer):\n assert(self.graph), \"Empty graph\"\n with self.graph.as_default():\n with tf.variable_scope(\"training\"):\n self.training_op = optimizer.minimize(self.loss)\n with tf.variable_scope(\"testing\"):\n self.correct = tf.nn.in_top_k(self.outputs, self.y, 1)\n self.accuracy = tf.reduce_mean(tf.cast(self.correct, tf.float32))\n with tf.variable_scope(\"summary\"):\n self.loss_summary = tf.summary.scalar(\"Loss\", self.loss)\n self.summary = tf.summary.merge_all()\n tf_log_dir = \"{}/{}_run-{}\".format(self.tf_log_dir, self.name, timestr())\n self.train_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"train\"), self.graph)\n self.valid_file_writer = tf.summary.FileWriter(os.path.join(tf_log_dir, \"valid\"), self.graph)\n with tf.variable_scope(\"global_initializer\"):\n self.init = tf.global_variables_initializer()\n with tf.variable_scope(\"saver\"):\n self.saver = tf.train.Saver()\n\n def save(self, model_path):\n with tf.Session(graph=self.graph) as sess:\n self.init.run()\n self.saver.save(sess, model_path)\n\n def restore(self, model_path):\n \"\"\"\n Restore model's params\n \"\"\"\n assert(self.graph), \"Invalid graph\"\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.initial_params = {}\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n \n def fit(self, X_train, X_valid, y_train, y_valid, model_path, save_best_only = True, n_epochs = 1000, batch_size = 256, checkpoint_steps = 100, seed = 42, tfdebug = False):\n assert(self.training_op is not None), \"Invalid self.training_op\"\n assert(self.X.shape[1] == X_train.shape[1]), \"Invalid input shape\"\n with tf.Session(graph=self.graph) as sess:\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if batch_size is None:\n batch_size = len(X_train)\n tf.set_random_seed(seed)\n self.init.run()\n self.initial_params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n best_loss_on_valid_set = 100000\n model_step = -1\n stop = False\n for epoch in tqdm(range(n_epochs)):\n X_train_indices = np.random.permutation(len(X_train))\n n_batches = len(X_train) // batch_size\n start_idx = 0\n for batch_idx in range(n_batches):\n indices = X_train_indices[start_idx : start_idx + batch_size]\n X_batch = X_train[indices]\n y_batch = y_train[indices]\n sess.run(self.training_op, feed_dict={self.X: X_batch, self.y: y_batch, self.training: True}) \n step = epoch * n_batches + batch_idx\n if step % checkpoint_steps == 0:\n train_summary = sess.run(self.summary, feed_dict={self.X: X_batch, self.y: y_batch})\n self.train_file_writer.add_summary(train_summary, step)\n loss_on_valid_set, loss_summary_on_valid_set = sess.run([self.loss, self.loss_summary],\n feed_dict={self.X: X_valid, self.y: y_valid})\n self.valid_file_writer.add_summary(loss_summary_on_valid_set, step)\n model_to_save = (not save_best_only) or (loss_on_valid_set < best_loss_on_valid_set)\n if loss_on_valid_set < best_loss_on_valid_set:\n best_loss_on_valid_set = loss_on_valid_set\n if model_to_save:\n self.saver.save(sess, model_path)\n model_step = step\n if os.path.exists(self.stop_file_path):\n stop = True\n start_idx += batch_size\n if stop:\n print(\"Stopping command detected: {}\".format(self.stop_file_path))\n break\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n self.train_file_writer.close()\n self.valid_file_writer.close()\n assert(model_step >= 0), \"Invalid model step\"\n all_steps = n_epochs * n_batches\n return model_step, all_steps\n\n def restore_and_eval(self, model_path, X, y = None, varlist = [], tfdebug = False):\n \"\"\"\n Restore model's params and evaluate variables\n\n Arguments:\n - X: the input to be fed into the network\n - varlist: list of variables to evaluate. Valid values: \"loss\", \"reconstruction_loss\", \"hidden_outputs\", \"outputs\"\n\n Return: a list of evaluated variables\n\n TODO: extend X to also accept a list of inputs; useful when evaluate with training and test sets so that \n the network needs to be restored once\n \"\"\"\n assert(self.graph), \"Invalid graph\"\n with tf.Session(graph=self.graph) as sess:\n self.saver.restore(sess, model_path)\n self.params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n if tfdebug:\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if not varlist:\n return []\n assert(X is not None), \"Invalid input samples\"\n varmap = {\"loss\": self.loss,\n \"hidden_outputs\": self.hidden[-1],\n \"outputs\": self.outputs,\n \"accuracy\": self.accuracy}\n vars_to_eval = []\n for var in varlist:\n # The order of var in the list needs to be kept, thus this for-loop\n if var == \"loss\":\n vars_to_eval += [self.loss]\n elif var == \"codings\":\n vars_to_eval += [self.encoders[-1]]\n elif var == \"outputs\":\n vars_to_eval += [self.outputs]\n elif var == \"accuracy\":\n assert(len(X) == len(y)), \"Invalid examples and targets sizes\"\n vars_to_eval += [self.accuracy]\n y = np.zeros((len(X), 1)) if y is None else y\n return sess.run(vars_to_eval, feed_dict={self.X: X, self.y: y})\n \n def get_codings(self, model_path, X, file_path = None):\n \"\"\"\n Compute the codings of an input by the network\n\n Arguments:\n - X: the input to be fed into the network with shape (n_examples, n_features)\n - file_path (optional): path to a csv file for storing the resulting codings\n\n Return: the codings of X with shape (n_examples, n_new_features)\n \"\"\"\n [X_codings] = self.restore_and_eval(model_path, X, varlist=[\"codings\"])\n assert(X.shape[0] == X_codings.shape[0]), \"Invalid number of rows in the codings\"\n if file_path is not None:\n columns = [\"f_{}\".format(idx) for idx in range(X_codings.shape[1])]\n df = pd.DataFrame(data=X_codings, columns=columns)\n df.to_csv(file_path)\n return X_codings\n\n \n##################################################################################\n##\n## StackBuilder class\n##\n##################################################################################\nclass StackBuilder:\n \"\"\"\n Utility class to build a stacked autoencoder with predefined specification\n \"\"\"\n def __init__(self,\n name,\n preceding_units = [],\n preceding_unit_model_paths = [],\n n_neurons_per_layer = [],\n unit_regularizer = [],\n unit_noise_stddev = [],\n unit_input_dropout_rate = [],\n unit_hidden_dropout_rate = [],\n stack_regularizer=None,\n stack_input_dropout_rate = 0,\n stack_hidden_dropout_rate = [],\n unit_hidden_activations = tf.nn.softmax, # of hidden layers\n unit_output_activations = None, # of hidden layers\n output_activation = tf.nn.softmax, # of output layer\n output_kernel_regularizer = None,\n output_kernel_initializer = tf.contrib.layers.variance_scaling_initializer(),\n output_bias_initializer = tf.zeros_initializer(),\n adam_lr = 5*1e-6,\n cache_dir = \"../cache\",\n tf_log_dir = \"../tf_logs\"):\n \"\"\"\n Ctor\n \n Arguments:\n - name: name of the stack\n - preceding_units: units that have been trained and will be reused\n - preceding_units_model_path: paths to model file of preceding units\n - n_neurons_per_layer: array of number of hidden neurons after the reused units\n - noise_stddev: array of noise_stddev to be used for new units after the reused ones\n - dropout_rate: similar to noise_stddev array\n\n \"\"\"\n self.name = name\n self.preceding_units = preceding_units\n self.preceding_unit_model_paths = preceding_unit_model_paths # for reuse trained unit autoencoders\n assert(len(self.preceding_units) == len(self.preceding_unit_model_paths)), \"Invalid preceding units\"\n self.n_neurons_per_layer = n_neurons_per_layer\n self.unit_regularizer = unit_regularizer\n self.unit_noise_stddev = unit_noise_stddev\n self.unit_input_dropout_rate = unit_input_dropout_rate\n self.unit_hidden_dropout_rate = unit_hidden_dropout_rate\n self.n_hidden_layers = len(self.n_neurons_per_layer) + len(self.preceding_units)\n if self.n_hidden_layers <= 0:\n raise ValueError(\"Stack cannot be created empty\")\n assert(len(self.unit_regularizer) == len(self.n_neurons_per_layer)), \"Invalid noise_stddev array\"\n assert(len(self.unit_noise_stddev) == len(self.n_neurons_per_layer)), \"Invalid noise_stddev array\"\n assert(len(self.unit_input_dropout_rate) == len(self.n_neurons_per_layer)), \"Invalid input dropout rate array\"\n assert(len(self.unit_hidden_dropout_rate) == len(self.n_neurons_per_layer)), \"Invalid hidden dropout rate array\"\n self.stack_regularizer=stack_regularizer\n self.stack_input_dropout_rate = stack_input_dropout_rate\n self.stack_hidden_dropout_rate = stack_hidden_dropout_rate\n assert(len(self.stack_hidden_dropout_rate) <= self.n_hidden_layers), \"Invalid hidden dropout rate\" \n self.unit_model_paths = [None] * self.n_hidden_layers\n self.units = [None] * self.n_hidden_layers\n self.unit_hidden_activations = unit_hidden_activations\n self.unit_output_activations = unit_output_activations\n self.output_activation = output_activation\n self.output_kernel_regularizer = output_kernel_regularizer\n self.output_kernel_initializer = output_kernel_initializer\n self.output_bias_initializer = output_bias_initializer\n self.adam_lr = adam_lr \n self.cache_dir = cache_dir\n self.tf_log_dir = tf_log_dir\n self.stack_cache_dir = os.path.join(self.cache_dir, \"stack\")\n self.stack_tf_log_dir = os.path.join(self.tf_log_dir, \"stack\")\n self.stack_model_path = os.path.join(self.stack_cache_dir, self.name) + \".model\"\n self.stack = None\n\n def _save_X(self, X, file_path):\n columns = [\"f_{}\".format(idx) for idx in range(X.shape[1])]\n df = pd.DataFrame(data=X, columns=columns)\n df.to_csv(file_path)\n\n def get_stack(self):\n return self.stack\n\n def get_units_and_model_paths(self):\n return self.units, self.unit_model_paths\n \n def build_pretrained_stack(self,\n X_train,\n X_valid,\n y_train,\n ordinary_stack = False,\n n_observable_hidden_neurons_per_layer = 0,\n n_hidden_neurons_to_plot = 20,\n n_reconstructed_examples_per_class_to_plot = 20,\n n_epochs = 10000,\n batch_size = 64,\n checkpoint_steps = 1000,\n pretrained_weight_initialization = True,\n restore_stack_model = True,\n seed = 42):\n assert(X_train.shape[1] == X_valid.shape[1]), \"Invalid input shapes\"\n units = []\n X_train_current = X_train\n X_valid_current = X_valid\n rows = {}\n for hidden_layer in range(self.n_hidden_layers):\n unit_name = \"Unit_{}\".format(hidden_layer)\n unit_cache_dir = os.path.join(self.cache_dir, unit_name)\n if not os.path.exists(unit_cache_dir):\n os.makedirs(unit_cache_dir)\n unit_tf_log_dir = os.path.join(self.tf_log_dir, unit_name)\n if not os.path.exists(unit_tf_log_dir):\n os.makedirs(unit_tf_log_dir)\n n_inputs = X_train_current.shape[1]\n is_preceding_unit = hidden_layer < len(self.preceding_units)\n n_neurons = self.preceding_units[hidden_layer].n_neurons if is_preceding_unit else self.n_neurons_per_layer[hidden_layer - len(self.preceding_units)]\n regularizer = self.preceding_units[hidden_layer].regularizer if is_preceding_unit else self.unit_regularizer[hidden_layer - len(self.preceding_units)]\n noise_stddev = self.preceding_units[hidden_layer].noise_stddev if is_preceding_unit else self.unit_noise_stddev[hidden_layer - len(self.preceding_units)]\n input_dropout_rate = self.preceding_units[hidden_layer].input_dropout_rate if is_preceding_unit else self.unit_input_dropout_rate[hidden_layer - len(self.preceding_units)]\n hidden_dropout_rate = self.preceding_units[hidden_layer].hidden_dropout_rate if is_preceding_unit else self.unit_hidden_dropout_rate[hidden_layer - len(self.preceding_units)]\n unit = UnitAutoencoder(unit_name,\n n_inputs,\n n_neurons,\n regularizer=regularizer,\n noise_stddev=noise_stddev,\n input_dropout_rate=input_dropout_rate,\n hidden_dropout_rate=hidden_dropout_rate,\n hidden_activation = self.unit_hidden_activations,\n output_activation = self.unit_output_activations,\n n_observable_hidden_neurons = n_observable_hidden_neurons_per_layer,\n optimizer = tf.train.AdamOptimizer(self.adam_lr),\n tf_log_dir = unit_tf_log_dir)\n \n # Try to reuse trained model if specified\n unit_model_path = self.preceding_unit_model_paths[hidden_layer] if hidden_layer < len(self.preceding_units) else os.path.join(unit_cache_dir, \"{}.model\".format(unit_name))\n if not os.path.exists(\"{}.meta\".format(unit_model_path)):\n if pretrained_weight_initialization:\n print(\"Training {} for hidden layer {}...\\n\".format(unit_name, hidden_layer))\n model_step, all_steps = unit.fit(X_train_current,\n X_valid_current,\n n_epochs=n_epochs,\n model_path=unit_model_path,\n batch_size=batch_size,\n checkpoint_steps=checkpoint_steps,\n seed=seed)\n print(\">> Done\\n\")\n print(\">> Best model saved at step {} out of {} total steps\\n\".format(model_step, all_steps))\n else:\n print(\"Randomly initialized weights and save model to {}...\\n\".format(unit_model_path))\n unit.save_untrained_model(model_path=unit_model_path, seed=seed)\n model_step, all_steps = (0, 0)\n print(\">> Done\\n\")\n print(\"Plotting reconstructed outputs of unit at hidden layer {}...\\n\".format(hidden_layer))\n unit_plot_dir = os.path.join(unit_cache_dir, \"plots\")\n [X_recon] = unit.restore_and_eval(X_train_current, unit_model_path, [\"outputs\"])\n assert(X_recon.shape == X_train_current.shape), \"Invalid output shape\"\n unit_reconstructed_dir = os.path.join(unit_plot_dir, \"reconstructed\")\n plot_reconstructed_outputs(X_train_current, y_train, X_recon, size_per_class=n_reconstructed_examples_per_class_to_plot,\n plot_dir_path=unit_reconstructed_dir, seed=seed+10)\n print(\">> Done\\n\")\n print(\"Plotting hidden weights of unit at hidden layer {}...\\n\".format(hidden_layer))\n hidden_weights = unit.hidden_weights()\n unit_hidden_weights_dir = os.path.join(unit_plot_dir, \"hidden_weights\")\n plot_hidden_weights(hidden_weights, n_hidden_neurons_to_plot, unit_hidden_weights_dir, seed =seed+20)\n print(\">> Done\\n\")\n else:\n print(\"Reloading model {} of {} for hidden layer {}...\\n\".format(unit_model_path, unit_name, hidden_layer))\n unit.restore(unit_model_path)\n model_step, all_steps = 0, 0\n print(\">> Done\\n\")\n self.unit_model_paths[hidden_layer] = unit_model_path # This can be passed to subsequent stack built upon this one\n self.units[hidden_layer] = unit\n self._save_X(X_train_current, os.path.join(unit_cache_dir, \"X_train_layer_{}.csv\".format(hidden_layer)))\n self._save_X(X_valid_current, os.path.join(unit_cache_dir, \"X_valid_layer_{}.csv\".format(hidden_layer)))\n [train_reconstruction_loss, X_train_current] = unit.restore_and_eval(X_train_current, unit_model_path, [\"reconstruction_loss\", \"hidden_outputs\"])\n [valid_reconstruction_loss, X_valid_current] = unit.restore_and_eval(X_valid_current, unit_model_path, [\"reconstruction_loss\", \"hidden_outputs\"])\n rows[hidden_layer] = [train_reconstruction_loss, valid_reconstruction_loss, model_step, all_steps, unit_model_path]\n \n print(\"Stacking up pretrained units...\\n\")\n self.stack = StackedAutoencoders(name=self.name, cache_dir=self.stack_cache_dir, tf_log_dir=self.stack_tf_log_dir)\n if (not ordinary_stack):\n stack_hidden_layer_names = [\"{}_hidden_{}\".format(self.name, str(idx)) for idx in range(len(self.units))]\n for idx, unit in enumerate(self.units):\n stack_input_dropout_rate = self.stack_input_dropout_rate if idx == 0 else 0\n stack_hidden_dropout_rate = self.stack_hidden_dropout_rate[idx] if idx < len(self.stack_hidden_dropout_rate) else 0\n stack_regularizer = self.stack_regularizer\n self.stack.stack_encoder(unit, stack_hidden_layer_names[idx],\n regularizer=stack_regularizer,\n input_dropout_rate=stack_input_dropout_rate,\n hidden_dropout_rate=stack_hidden_dropout_rate)\n self.stack.stack_softmax_output_layer(layer_name=\"{}_softmax_outputs\".format(self.name),\n kernel_regularizer=self.output_kernel_regularizer,\n kernel_initializer=self.output_kernel_initializer,\n bias_initializer=self.output_bias_initializer)\n else:\n assert(False), \"Not implemented\"\n stack_encoder_layer_names = [\"{}_encoder_{}\".format(self.name, str(idx)) for idx in range(len(self.units))]\n for idx, unit in enumerate(self.units):\n self.stack.stack_encoder(unit, stack_encoder_layer_names[idx])\n stack_decoder_layer_names = [\"{}_decoder_{}\".format(self.name, str(idx)) for idx in range(len(self.units))]\n for idx, unit in enumerate(reversed(self.units)):\n is_reconstruction_layer = (idx == len(self.units) - 1)\n self.stack.stack_decoder(unit, stack_decoder_layer_names[idx], is_reconstruction_layer=is_reconstruction_layer)\n self.stack.finalize(optimizer=tf.train.AdamOptimizer(self.adam_lr))\n print(\">> Done\\n\")\n if (not restore_stack_model):\n print(\"Saving stack model to {}...\\n\".format(self.stack_model_path))\n self.stack.save(self.stack_model_path)\n print(\">> Done\\n\")\n else:\n assert(os.path.exists(\"{}.meta\".format(self.stack_model_path))), \"Stack model path not found\"\n print(\"Restoring stack model from {}...\\n\".format(self.stack_model_path))\n self.stack.restore(self.stack_model_path)\n print(\">> Done\\n\")\n \n result_file_path = os.path.join(self.stack_cache_dir, \"hidden_layer_units.csv\")\n print(\"Saving results of building hidden layer units to {}...\\n\".format(result_file_path))\n columns = [\"train_reconstruction_loss\", \"valid_reconstruction_loss\", \"step_of_best_model\", \"all_steps\", \"unit_model_path\"]\n df = pd.DataFrame.from_dict(rows, orient=\"index\")\n df.index.name = \"hidden_layer\"\n df.columns = columns\n df.sort_index(inplace=True)\n df.to_csv(result_file_path)\n print(\">> Done\\n\")\n \n \n##################################################################################\n##\n## Supporting functions\n##\n##################################################################################\ndef generate_unit_autoencoders(X_train,\n X_valid,\n y_train,\n y_valid,\n scaler,\n n_neurons_range,\n n_folds = 10,\n noise_stddev = None,\n dropout_rate = None,\n hidden_activation = tf.nn.softmax,\n output_activation = None,\n regularizer_value = None,\n initializer = tf.contrib.layers.variance_scaling_initializer(),\n optimizer = tf.train.AdamOptimizer(0.001),\n n_epochs = 5000,\n batch_size = 256,\n checkpoint_steps = 100,\n n_observable_hidden_neurons = 1.0,\n n_hidden_neurons_to_plot = 1.0,\n n_reconstructed_examples_per_class_to_plot = 20,\n seed = 0, \n cache_dir = \"../cache\",\n tf_log_dir = \"../tf_logs\"):\n n_inputs = X_train.shape[1]\n if not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\n if noise_stddev is not None:\n prefix = \"denoise\"\n elif dropout_rate is not None:\n prefix = \"dropout\"\n else:\n prefix = \"ordinary\"\n all_run_rows = {}\n all_run_idx = 0\n avg_recon_loss_rows = {}\n all_indices = list(np.random.permutation(len(X_train)))\n fold_sz = len(all_indices) // n_folds\n for n_neurons in n_neurons_range:\n avg_recon_loss = 0\n for fold_idx in range(n_folds):\n unit_name = config_str(prefix,\n n_epochs=n_epochs,\n n_inputs=n_inputs,\n n_neurons=n_neurons,\n hidden_activation=hidden_activation,\n regularizer_value=regularizer_value,\n noise_stddev=noise_stddev,\n dropout_rate=dropout_rate)\n unit_name += \"_fold{}\".format(fold_idx)\n print(\"\\n\\n*** Constructing and training unit {}, fold {}/{} ***\".format(unit_name, fold_idx+1, n_folds))\n unit_cache_dir = os.path.join(cache_dir, unit_name)\n if not os.path.exists(unit_cache_dir):\n os.makedirs(unit_cache_dir)\n unit_tf_log_dir = tf_log_dir\n if not os.path.exists(unit_tf_log_dir):\n os.makedirs(unit_tf_log_dir)\n unit_regularizer = tf.contrib.layers.l2_regularizer(regularizer_value) if regularizer_value is not None else None\n unit = UnitAutoencoder(unit_name,\n n_inputs,\n n_neurons,\n n_observable_hidden_neurons=n_observable_hidden_neurons,\n noise_stddev=noise_stddev,\n dropout_rate=dropout_rate,\n hidden_activation=hidden_activation,\n output_activation=output_activation,\n regularizer=unit_regularizer,\n initializer=initializer,\n optimizer=optimizer, \n tf_log_dir=unit_tf_log_dir)\n unit_model_path = os.path.join(unit_cache_dir, \"{}.model\".format(unit_name))\n fold_start_idx = int(fold_idx * fold_sz)\n fold_end_idx = min(fold_start_idx + fold_sz, len(all_indices))\n if fold_end_idx - fold_start_idx == len(all_indices):\n X_train_indices = range(len(all_indices))\n else:\n X_train_indices = all_indices[:fold_start_idx] + all_indices[fold_end_idx:]\n X_train_scaled = scaler.fit_transform(X_train[X_train_indices])\n X_valid_scaled = scaler.transform(X_valid)\n model_step = unit.fit(X_train_scaled,\n X_valid_scaled,\n n_epochs=n_epochs,\n model_path=unit_model_path,\n batch_size=batch_size,\n checkpoint_steps=checkpoint_steps,\n seed=seed)\n print(\"\\n>> Model {} saved at step {}\\n\".format(unit_model_path, model_step))\n [reconstruction_loss, outputs] = unit.restore_and_eval(X_train_scaled, unit_model_path, [\"reconstruction_loss\", \"outputs\"])\n all_run_row = [n_neurons, fold_idx, reconstruction_loss, unit_name]\n all_run_rows[all_run_idx] = all_run_row\n all_run_idx += 1\n assert(outputs.shape == X_train_scaled.shape), \"Invalid output shape\"\n unit_plot_dir = os.path.join(unit_cache_dir, \"plots\")\n unit_reconstructed_dir = os.path.join(unit_plot_dir, \"reconstructed\")\n X_recon = scaler.inverse_transform(outputs)\n plot_reconstructed_outputs(X_train[X_train_indices], y_train[X_train_indices], X_recon, size_per_class=n_reconstructed_examples_per_class_to_plot,\n plot_dir_path=unit_reconstructed_dir, seed=seed+10)\n hidden_weights = unit.hidden_weights()\n unit_hidden_weights_dir = os.path.join(unit_plot_dir, \"hidden_weights\")\n plot_hidden_weights(hidden_weights, n_hidden_neurons_to_plot, unit_hidden_weights_dir, seed =seed+20)\n\n # Cross validation on the remaining examples\n X_remaining_indices = all_indices[fold_start_idx:fold_end_idx]\n X_remaining_scaled = scaler.transform(X_train[X_remaining_indices])\n [valid_reconstruction_loss] = unit.restore_and_eval(X_remaining_scaled, unit_model_path, [\"reconstruction_loss\"])\n avg_recon_loss += valid_reconstruction_loss\n avg_recon_loss /= n_folds\n avg_recon_loss_rows[n_neurons] = [avg_recon_loss]\n \n columns = [\"n_neurons\", \"fold_idx\", \"reconstruction_loss\", \"model_name\"]\n all_runs_df = pd.DataFrame.from_dict(all_run_rows, orient=\"index\")\n all_runs_df.index.name = \"Idx\"\n all_runs_df.columns = columns\n result_file_path = os.path.join(cache_dir, \"results_all_runs.csv\")\n if os.path.exists(result_file_path):\n existing_df = pd.DataFrame.from_csv(result_file_path, index_col = 0)\n all_runs_df = all_runs_df.append(existing_df)\n all_runs_df.sort_index(inplace=True)\n all_runs_df.to_csv(result_file_path)\n\n columns = [\"reconstruction_loss\"]\n avg_df = pd.DataFrame.from_dict(avg_recon_loss_rows, orient=\"index\")\n avg_df.index.name = \"n_neurons\"\n avg_df.columns = columns\n result_file_path = os.path.join(cache_dir, \"results_avg.csv\")\n if os.path.exists(result_file_path):\n existing_df = pd.DataFrame.from_csv(result_file_path, index_col = 0)\n avg_df = avg_df.append(existing_df)\n avg_df.sort_index(inplace=True)\n avg_df.to_csv(result_file_path)\n \n","sub_path":"report_submit/StackedAutoencoders.py","file_name":"StackedAutoencoders.py","file_ext":"py","file_size_in_byte":52251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"555185082","text":"#!/usr/bin/env python\n#Monday, January 2 2017\n# Code for parsing raw data (raw_responses_2016.csv) to gexf file\n\nimport json\nimport random\n\n\nmyfile = open('data.txt', 'r')\nlines = myfile.readlines()\nmyfile.close()\n\nnodes = []\nedges = []\nindexDict = {}\n#use this to keep track of matches that have already occured \nmatchesEntered = {}\nfor nodeIndex, line in enumerate(lines):\t\n\t# unpack values\n\tline = line.strip('\\n')\n\tsplits = line.split(':')\n\tId = splits[0]\n\tyear = splits[1]\n\thouse = splits[2]\n\tgender = splits[3] \n\tinterestedIn = splits[4] #gender\n\t# create dictionary\n\tnode_dict = {'Id' : Id, 'Year' : year, 'House' : house, 'Gender' : gender, 'Interest' : interestedIn}\n\t# Add dictionary to list\n\tnodes.append(node_dict)\n\tmatches = splits[5:len(splits)]\n\t# keep track of the node's index\n\tindexDict[Id] = {}\n\tindexDict[Id]['matches'] = matches\n\tindexDict[Id]['index'] = nodeIndex\n\t# create an array to hold all the connections that have been added\n\tmatchesEntered[Id] = []\n\n\n\n### MAKE SPOOF DICTIONARY\nspoofDict = dict()\noptions = set(indexDict.keys())\nfor key in indexDict:\n\tspoofId = key\n\twhile(spoofId == key):\n\t\tspoofId = random.sample(options, 1)[0]\n\t\tif (len(options) == 1):\n\t\t\tbreak\n\toptions.remove(spoofId)\n\tspoofDict[key] = spoofId\n\n### Change the nodes array \nnewNodes =[]\nfor j in nodes: \n\tnewId = spoofDict[j['Id']]\n\t#print(\"OLD ID: \" + str(j['Id']) + \"\\t NEW ID\\t \" + str(newId) + \"\\n\")\n\tj['Id'] = newId\n\tnewNodes.append(j)\n\n# Once we've finished building this indexDict, loop through to build edges\nfor key in indexDict:\n\t# Only take the first 3 matches\n\tmatches = indexDict[key]['matches'][0:3]\n\t# Only take the first match\n\t# matches = indexDict[key]['matches'][0:1]\n\tsourceIndex = indexDict[key]['index']\n\tfor match in matches:\n\t\t#q1 is eligible\n\t\t#q2 means this person wants to match\n\t\t#q3 means the other person wants to match\n\t\ttarget, q1, q2, q3 = match.split(\",\")\n\t\tsourceNode = key\n\t\ttargetNode = target\n\t\tif targetNode in matchesEntered.keys():\n\t\t\t# Filter out edges we've already tracked\n\t\t\tif sourceNode not in matchesEntered[targetNode]:\n\t\t\t\t# Keep track of this so we can filter in the future\n\t\t\t\tmatchesEntered[sourceNode].append(targetNode)\n\n\t\t\t\t# Get the target's key\n\t\t\t\tif target in indexDict.keys():\n\t\t\t\t\ttargetIndex = indexDict[target]['index']\n\t\t\t\t\t# Source ndoe and target node \n\t\t\t\t\t# Changing this so that it's by source node and target node..\n\t\t\t\t\t# To change back: sourceIndex and targetIndex \n\t\t\t\t\tconnection_dict = {'source':int(spoofDict[sourceNode]), 'target':int(spoofDict[targetNode]), 'eligible':q1, 'interested':q2, 'reverse interest':q3}\n\t\t\t\t\tedges.append(connection_dict)\nmyOutput = {'nodes':newNodes, 'edges':edges}\nprint(json.dumps(myOutput))\n","sub_path":"pyscripts/parse_network.py","file_name":"parse_network.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"5765588","text":"\"\"\"\nThis script will report on the data from the 'Regelgeving' and any possibility from Uitwisselingsplatform.\n\"\"\"\n# Allow lib to library import path.\nimport os\nimport sys\n(pp, cd) = os.path.split(os.getcwd())\nsys.path.append(pp)\n\n# import logging\nfrom lib import my_env\nfrom lib import mysqlstore as mysql\nfrom lib.mysqlstore import *\n\n\ndef list_of_tx(arcomp, comp_id, prev_comp=None):\n \"\"\"\n This function will get all the translations for a specific Archief component. In case there is one or more\n translation in the Uitwisselingsplatform, a list of all translations will be provided.\n In case there is no translation, then a list with a single value (\" . \") will be provided. This way we are sure\n that the Archief Component is listed.\n @param arcomp: Class for the Archief Component (ArType, ArFase, ArStap, ArDocument)\n @param comp_id: ID for the Archief component\n @param prev_comp: If previous component is not translated, then this component does not need to be translated\n @return: List of translations.\n \"\"\"\n not_translated = \" . \"\n list_tx = []\n if prev_comp != not_translated:\n for upcomps in cons_sess.query(arcomp).filter_by(id=comp_id).filter(arcomp.upcomps.any()):\n for upcomp in upcomps.upcomps:\n list_tx.append(upcomp.naam)\n if len(list_tx) == 0:\n list_tx.append(not_translated)\n return list_tx\n\n\nif __name__ == \"__main__\":\n\n cfg = my_env.init_env(\"convert_protege\", __file__)\n\n # Get session for Consolidation Database\n cons_sess = mysql.init_session(db=cfg[\"ConsolidationDB\"][\"db\"],\n user=cfg[\"ConsolidationDB\"][\"user\"],\n pwd=cfg[\"ConsolidationDB\"][\"pwd\"],\n echo=False)\n\n fn = os.path.join(cfg['Main']['reportdir'], \"dn3_platform_archief.csv\")\n with open(fn, 'w') as fh:\n fh.write(\"dossiertype;fase;stap;;dossiertype;fase;stap\\n\")\n for artype in cons_sess.query(ArType).filter(ArType.fases.any()):\n for uptype in list_of_tx(ArType, artype.id):\n for arfase in artype.fases:\n for upfase in list_of_tx(ArFase, arfase.id, prev_comp=uptype):\n for arstap2fase in cons_sess.query(ArFase).filter_by(id=arfase.id).filter(ArFase.stappen.any()):\n for arstap in arstap2fase.stappen:\n for upstap in list_of_tx(ArStap, arstap.id, prev_comp=upfase):\n fh.write(\"{d};{f};{s};;{uptype};{upfase};{upstap}\\n\"\n .format(d=artype.naam, f=arfase.naam, s=arstap.naam,\n uptype=uptype, upfase=upfase, upstap=upstap))\n\n fn = os.path.join(cfg['Main']['reportdir'], \"dn4_platform_archief.csv\")\n with open(fn, 'w') as fh:\n fh.write(\"dossiertype;fase;stap;document;;dossiertype;fase;stap;document\\n\")\n for artype in cons_sess.query(ArType).filter(ArType.fases.any()):\n for uptype in list_of_tx(ArType, artype.id):\n for arfase in artype.fases:\n for upfase in list_of_tx(ArFase, arfase.id, prev_comp=uptype):\n for arstap2fase in cons_sess.query(ArFase).filter_by(id=arfase.id).filter(ArFase.stappen.any()):\n for arstap in arstap2fase.stappen:\n for upstap in list_of_tx(ArStap, arstap.id, prev_comp=upfase):\n for ardocument2stap in cons_sess.query(ArStap).filter_by(id=arstap.id)\\\n .filter(ArStap.documenten.any()):\n for ardocument in ardocument2stap.documenten:\n for updocument in list_of_tx(ArDocument, ardocument.id, prev_comp=upstap):\n fh.write(\"{d};{f};{s};{ardoc};;{uptype};{upfase};{upstap};{updoc}\\n\"\n .format(d=artype.naam, f=arfase.naam, s=arstap.naam,\n ardoc=ardocument.naam,\n uptype=uptype, upfase=upfase, upstap=upstap,\n updoc=updocument))\n\nlogging.info('End Application')\n","sub_path":"Python/source_consolidation/report_archief_platform.py","file_name":"report_archief_platform.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"359081773","text":"# Copyright (C) 2014 Canonical Ltd.\n# Author: Michael Vogt \n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 3 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n\"\"\"Integration tests for the click chroot feature.\"\"\"\n\nimport subprocess\nimport unittest\n\nfrom .helpers import (\n require_network,\n require_root,\n ClickTestCase,\n)\n\n# architectures present in 14.04 (current default framework)\nALLOW_ARCHITECTURES = [\n \"amd64\", \"arm64\", \"armhf\", \"i386\", \"powerpc\", \"ppc64el\"]\n\n\ndef skipUnlessAllowedArchitecture():\n system_arch = subprocess.check_output(\n [\"dpkg\", \"--print-architecture\"], universal_newlines=True).strip()\n if system_arch in ALLOW_ARCHITECTURES:\n return lambda func: func\n else:\n return unittest.skip(\"%s does not exist in 14.04\")\n\n\n@skipUnlessAllowedArchitecture()\nclass TestChroot(ClickTestCase):\n\n @classmethod\n def command(cls, arch, *args):\n return [cls.click_binary, \"chroot\", \"-a\", arch] + list(args)\n\n @classmethod\n def setUpClass(cls):\n super(TestChroot, cls).setUpClass()\n require_root()\n require_network()\n cls.arch = subprocess.check_output(\n [\"dpkg\", \"--print-architecture\"], universal_newlines=True).strip()\n subprocess.check_call(cls.command(cls.arch, \"create\"))\n\n @classmethod\n def tearDownClass(cls):\n subprocess.check_call(cls.command(cls.arch, \"destroy\"))\n\n def test_upgrade(self):\n subprocess.check_call(self.command(self.arch, \"upgrade\"))\n\n def test_install(self):\n subprocess.check_call(self.command(self.arch, \"install\", \"apt-utils\"))\n\n def test_run(self):\n output = subprocess.check_output(\n self.command(self.arch, \"run\", \"echo\", \"hello world\"),\n universal_newlines=True)\n self.assertEqual(output, \"hello world\\n\")\n\n def test_maint(self):\n output = subprocess.check_output(\n self.command(self.arch, \"maint\", \"id\"),\n universal_newlines=True)\n self.assertEqual(output, \"uid=0(root) gid=0(root) groups=0(root)\\n\")\n\n def test_exists_ok(self):\n subprocess.check_call(self.command(self.arch, \"exists\"))\n\n def test_exists_no(self):\n with self.assertRaises(subprocess.CalledProcessError):\n subprocess.check_call(\n self.command(\"arch-that-does-not-exist\", \"exists\"))\n\n\nclass TestChrootName(TestChroot):\n \"\"\"Run the chroot tests again with a different --name.\"\"\"\n\n @classmethod\n def command(cls, arch, *args):\n return super(TestChrootName, cls).command(\n arch, \"-n\", \"testname\", *args)\n\n def test_exists_different_name_fails(self):\n # \"click chroot exists\" fails for a non-existent name.\n with self.assertRaises(subprocess.CalledProcessError):\n subprocess.check_call(super(TestChrootName, self).command(\n self.arch, \"-n\", \"testname2\", \"exists\"))\n","sub_path":"click/tests/integration/test_chroot.py","file_name":"test_chroot.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"92024670","text":"#! /usr/bin/env python2\n\ndef main():\n\n #\n # Imports & globals\n #\n global args, summaryInstance, sys, time, pysam\n import pysam, sys, time\n\n #\n # Argument parsing\n #\n argumentsInstance = readArgs()\n processor_count = readArgs.processors(argumentsInstance)\n\n #\n # Initials\n #\n summaryInstance = Summary()\n window = args.window_size\n past_unpaired_reads = dict()\n\n currentPhaseBlocks = CurrentPhaseBlocks()\n rp_max_dist = 50000\n\n current_limit = 1000000\n\n report_progress('Fetching cache reads')\n\n with pysam.AlignmentFile(args.sort_tag_bam, 'rb') as infile:\n\n for chromosome_header in infile.header['SQ']:\n\n chromosome_name = chromosome = chromosome_header['SN']\n chromosome_length = chromosome_header['LN']\n\n for read in infile.fetch(chromosome_name, 0, chromosome_length):\n\n summaryInstance.reads += 1\n\n if summaryInstance.reads >= current_limit:\n report_progress(\"{:,}\".format(summaryInstance.reads) + ' reads fetched')\n current_limit += 1000000\n\n # Stores read until its mate occurs in file\n # NB: mate will always be upstream of read!\n try: mate = past_unpaired_reads[read.query_name]\n except KeyError:\n past_unpaired_reads[read.query_name] = read\n continue\n\n # Drop read from tmp storage when mate is found\n del past_unpaired_reads[read.query_name]\n\n # Fetch positions\n mate_start, mate_stop = mate.get_reference_positions()[0], mate.get_reference_positions()[-1]\n read_start, read_stop = read.get_reference_positions()[0], read.get_reference_positions()[-1]\n\n # Standardise read positions according to refernce instead of read direction.\n mate_start, mate_stop = direct_read_pairs_to_ref(mate_start, mate_stop)\n read_start, read_stop = direct_read_pairs_to_ref(read_stop, read_start)\n\n # If read pairs are ridiculously far apart (50 kb), just count reads as unpaired\n if mate_stop + rp_max_dist < read_start:\n summaryInstance.unpaired_reads += 2\n summaryInstance.unpaired_reads_in_same_chr += 2\n continue\n\n # Calculates % read bases of insert, aka (bp_r1 + bp_r2) / (bp_r1 + bp_r2 + bp_btw_rp)\n percent_coverage = read_pair_coverage(mate_start, mate_stop, read_start, read_stop)\n barcode_id = read.get_tag('RG')\n\n # Intitates phase blocks with name = barcode_ID, if not that phase block exist, then fetches last pos(phase block)\n try: last_pos_of_phase_block = currentPhaseBlocks.dictionary[barcode_id]['stop']\n except KeyError:\n # Initiate new entry with (start, stop, # reads)\n currentPhaseBlocks.initiatePhaseBlock(name=barcode_id, start=mate_start, stop=read_stop, rp_coverage=percent_coverage)\n continue\n\n # If last position of phase block is withing window (100 kb) distance of current read, then add this read to phase block.\n if (last_pos_of_phase_block+window) >= mate_start:\n currentPhaseBlocks.addReadPairToPhaseBlock(phase_block=barcode_id, rp_start=mate_start, rp_stop=read_stop, rp_coverage=percent_coverage)\n\n # If read is outside range of window from last position, then report the old phase block and initate a new one.\n else:\n\n # Normalises average coverage for number of reads when grand total is known.\n summaryInstance.reportPhaseBlock(currentPhaseBlocks.dictionary[barcode_id], barcode_id)\n currentPhaseBlocks.terminatePhaseBlock(phase_block=barcode_id)\n\n # Initiate new entry with (start, stop, # reads)\n currentPhaseBlocks.initiatePhaseBlock(name=barcode_id, start=mate_start, stop=read_stop, rp_coverage=percent_coverage)\n\n # Will rinse/count unpaired reads in between chromosomes\n summaryInstance.unpaired_reads += len(past_unpaired_reads.keys())\n past_unpaired_reads = dict()\n\n # Report phase blocks when switching to new chromosome, as not to confuse positions\n currentPhaseBlocks.commitAndRemoveAll()\n\n report_progress('Phase blocks analysed')\n\n summaryInstance.writeResultFiles()\n\n # GREPFRICK: move to summary somewhere\n sys.stderr.write('\\nReads found (not read pairs) in bam:\\t' + \"{:,}\".format(summaryInstance.reads) + '\\n')\n sys.stderr.write('\\nUnpaired reads (removed from analysis):\\t' + \"{:,}\".format(summaryInstance.unpaired_reads) + '\\n')\n sys.stderr.write('In the same chromosome:\\t' + \"{:,}\".format(summaryInstance.unpaired_reads_in_same_chr) + '\\n')\n sys.stderr.write('(Defined as being ' + \"{:,}\".format(rp_max_dist) + ' bp apart)\\n')\n sys.stderr.write('\\nPhase blocks identified:\\t' + \"{:,}\".format(summaryInstance.phase_block_counter) + '\\n')\n sys.stderr.write('Phase blocks with only one read:\\t' + \"{:,}\".format(summaryInstance.phase_block_with_only_one_read_pair) + '\\n')\n\ndef direct_read_pairs_to_ref(read_start, read_stop):\n \"\"\"\n Reads can be aligned in forward and backwards direction, this puts all start/stops according to reference positions\n \"\"\"\n\n # if read backwards, turn it the other way\n if read_start > read_stop:\n return read_stop, read_start\n # Otherwise, return it as is\n else:\n return read_start, read_stop\n\ndef read_pair_coverage(mate_start, mate_stop, read_start, read_stop):\n \"\"\"\n This function calculates the percentage of read bases in the insert.\n \"\"\"\n\n # If reads overlap, cov = 1\n if mate_stop >= read_start:\n percent_coverage = 1\n # Otherwise, calc. % covered bases\n else:\n mate_bp = mate_stop - mate_start\n read_bp = read_stop - read_start\n uncovered_bases = read_start - mate_stop\n percent_coverage = (mate_bp + read_bp) / (uncovered_bases + mate_bp + read_bp)\n\n return percent_coverage\n\ndef report_progress(string):\n \"\"\"\n Writes a time stamp followed by a message (=string) to standard out.\n Input: String\n Output: [date] string\n \"\"\"\n sys.stderr.write(time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) + '\\t' + string + '\\n')\n\nclass CurrentPhaseBlocks(object):\n \"\"\"\n Tmp storage for phase blocks which might still get more reads assigned to them. Basically a dict with customised functions.\n \"\"\"\n\n def __init__(self):\n self.dictionary = dict()\n\n def initiatePhaseBlock(self, name, start, stop, rp_coverage):\n\n summaryInstance.phase_block_counter += 1\n\n self.dictionary[name] = dict()\n self.dictionary[name]['start'] = start\n self.dictionary[name]['stop'] = stop\n self.dictionary[name]['coverage'] = rp_coverage\n self.dictionary[name]['number_of_reads'] = 2\n self.dictionary[name]['insert_bases'] = stop - start\n self.dictionary[name]['bases_btw_inserts'] = 0\n\n def addReadPairToPhaseBlock(self, phase_block, rp_start, rp_stop, rp_coverage):\n self.dictionary[phase_block]['insert_bases'] += rp_stop - rp_start\n self.dictionary[phase_block]['bases_btw_inserts'] += rp_start - self.dictionary[phase_block]['stop']\n self.dictionary[phase_block]['stop'] = rp_stop\n self.dictionary[phase_block]['coverage'] += rp_coverage\n self.dictionary[phase_block]['number_of_reads'] += 2\n\n def terminatePhaseBlock(self, phase_block):\n\n del self.dictionary[phase_block]\n\n def commitAndRemoveAll(self):\n\n for phase_block in self.dictionary.copy().keys():\n summaryInstance.reportPhaseBlock(self.dictionary[phase_block], phase_block)\n del self.dictionary[phase_block]\n\nclass ProgressBar(object):\n \"\"\"\n Writes a progress bar to stderr\n \"\"\"\n\n def __init__(self, name, min, max, step):\n # Variables\n self.min = min\n self.max = max\n self.current_position = min\n self.step = step\n\n # Metadata\n self.two_percent = (self.max-self.min)/50\n self.current_percentage = self.two_percent\n\n # Printing\n report_progress(name)\n sys.stderr.write('\\n' + str(name))\n sys.stderr.write('\\n|------------------------------------------------|\\n')\n\n def update(self):\n # If progress is over 2%, write '#' to stdout\n self.current_position += self.step\n if self.current_percentage < self.current_position:\n sys.stderr.write('#')\n sys.stderr.flush()\n time.sleep(0.001)\n self.current_percentage += self.two_percent\n\n def terminate(self):\n sys.stderr.write('\\n')\n\nclass readArgs(object):\n \"\"\"\n Reads arguments and handles basic error handling like python version control etc.\n \"\"\"\n\n def __init__(self):\n\n readArgs.parse(self)\n readArgs.pythonVersion(self)\n\n def parse(self):\n\n #\n # Imports & globals\n #\n import argparse, multiprocessing\n global args\n\n parser = argparse.ArgumentParser(description=__doc__)\n\n # Arguments\n parser.add_argument(\"sort_tag_bam\", help=\".bam file tagged with @RG tags and duplicates marked (not taking \"\n \"cluster id into account).\")\n parser.add_argument(\"output_prefix\", help=\"prefix for results files (.read_pair_coverage, .coupling_efficiency, \"\n \".reads_per_molecule, .molecule_per_barcode and .phase_block_lengths\")\n\n # Options\n parser.add_argument(\"-F\", \"--force_run\", action=\"store_true\", help=\"Run analysis even if not running python 3. \"\n \"Not recommended due to different function \"\n \"names in python 2 and 3.\")\n parser.add_argument(\"-p\", \"--processors\", type=int, default=multiprocessing.cpu_count(),\n help=\"Thread analysis in p number of processors. \\nDEFAULT: all available\")\n parser.add_argument(\"-w\", \"--window_size\", type=int, default=100000, help=\"Window size cutoff for maximum distance \"\n \"in between two reads in one phase block. \"\n \"DEFAULT: 100,000 bp\")\n\n args = parser.parse_args()\n\n def pythonVersion(self):\n \"\"\" Makes sure the user is running python 3.\"\"\"\n\n #\n # Version control\n #\n import sys\n if sys.version_info.major == 3:\n pass\n else:\n sys.stderr.write('\\nWARNING: you are running python ' + str(\n sys.version_info.major) + ', this script is written for python 3.')\n if not args.force_run:\n sys.stderr.write('\\nAborting analysis. Use -F (--Force) to run anyway.\\n')\n sys.exit()\n else:\n sys.stderr.write('\\nForcing run. This might yield inaccurate results.\\n')\n\n def processors(self):\n\n #\n # Processors\n #\n import multiprocessing\n processor_count = args.processors\n max_processor_count = multiprocessing.cpu_count()\n if processor_count == max_processor_count:\n pass\n elif processor_count > max_processor_count:\n sys.stderr.write(\n 'Computer does not have ' + str(processor_count) + ' processors, running with default (' + str(\n max_processor_count) + ')\\n')\n processor_count = max_processor_count\n else:\n sys.stderr.write('Running with ' + str(processor_count) + ' processors.\\n')\n\n return processor_count\n\nclass Summary(object):\n\n def __init__(self):\n\n # Just defining numbers which will be assigned later\n self.reads = int()\n self.phase_blocks = int()\n self.bc_clusters = int()\n\n self.phase_block_lengths = dict()\n self.phase_blocks_per_cluster = dict()\n self.reads_per_phase_block = dict()\n\n self.ave_coverage_phase_block = int()\n self.ave_bases_read_in_read_pair = int()\n\n self.phase_block_result_dict = dict()\n\n self.unpaired_reads = int()\n self.unpaired_reads_in_same_chr = int()\n\n self.phase_block_with_only_one_read_pair = int()\n self.phase_block_counter = int()\n\n def reportPhaseBlock(self, phase_block, barcode_id):\n\n start = phase_block['start']\n stop = phase_block['stop']\n length = stop-start\n num_reads = phase_block['number_of_reads']\n ave_read_pair_coverage = phase_block['coverage'] / num_reads\n\n # Don't want ZeroDivision error\n if phase_block['bases_btw_inserts'] == 0:\n ave_phase_block_cov = 1\n else:\n ave_phase_block_cov = phase_block['insert_bases']/(phase_block['bases_btw_inserts'] + phase_block['insert_bases'])\n\n # Tries to append to list of tuples, otherwise creates a tuple list as value for given barcode id\n try: self.phase_block_result_dict[barcode_id]\n except KeyError:\n self.phase_block_result_dict[barcode_id] = list()\n\n # Save in summary dictionary\n self.phase_block_result_dict[barcode_id].append((start, stop, length, num_reads, ave_read_pair_coverage, ave_phase_block_cov))\n\n def writeResultFiles(self):\n\n # Opening all files\n molecules_per_bc_out = open((args.output_prefix + '.molecules_ber_bc'), 'w')\n coupling_out = open((args.output_prefix + '.coupling_efficiency'), 'w')\n ave_read_pair_coverage_out = open((args.output_prefix + '.ave_read_pair_coverage_in_phase_block'), 'w')\n reads_per_phase_block_out = open((args.output_prefix + '.reads_per_molecule'), 'w')\n phase_block_len_out = open((args.output_prefix + '.phase_block_lengths'), 'w')\n\n progressBar = ProgressBar(name='Writing output', min=0, max = summaryInstance.phase_block_counter, step = 1)\n\n # Writing outputs\n for barcode_id in self.phase_block_result_dict.keys():\n\n molecules_per_bc_out.write(str(len(self.phase_block_result_dict[barcode_id])) + '\\n')\n\n for phase_block in self.phase_block_result_dict[barcode_id]:\n\n reads_per_phase_block_out.write(str(phase_block[3]) + '\\n')\n ave_read_pair_coverage_out.write(str(phase_block[4]) + '\\n')\n\n # Not interesting if number of reads found are 1\n if phase_block[3] > 2:\n summaryInstance.phase_block_with_only_one_read_pair += 1\n phase_block_len_out.write(str(phase_block[2]) + '\\n')\n coupling_out.write(str(phase_block[5]/0.5) + '\\n')\n\n progressBar.update()\n\n # Close files\n for output_file in (molecules_per_bc_out, coupling_out, ave_read_pair_coverage_out, reads_per_phase_block_out, phase_block_len_out):\n output_file.close()\n\n progressBar.terminate()\n\nif __name__==\"__main__\": main()","sub_path":"python scripts/cluster_stats.py","file_name":"cluster_stats.py","file_ext":"py","file_size_in_byte":15408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"27457575","text":"def xor(state, inputs, length, invert):\n \"\"\"Computes XOR digital logic\n\n Parameters:\n\n :param str state : Current state of the register\n :param list inputs: Position to tap inputs from register\n Returns:\n\n :return output: Output of the XOR gate digital logic\n :rtype int :\n \"\"\"\n\n # Obtain bits to feed into Xor gate given index value\n input_a = int(state[inputs[0]])\n input_b = int(state[inputs[1]])\n\n result = bool((input_a & ~input_b) | (~input_a & input_b))\n\n # Checks if an XNOR is needed\n if invert is True: result = not result\n\n # Shift result of xor to MSB\n return result << length\n\n\nif __name__ == \"__main__\":\n\n current_state = \"001\"\n\n # Position to tap for Xor gate\n index_inputs = [0, 2]\n max_clock = 100\n invert = False\n\n for clock in range(0, max_clock + 1):\n\n print(clock, current_state)\n\n xor_output = xor(current_state, index_inputs, len(current_state) - 1,\n invert)\n\n shift = int(current_state, 2) >> 1\n\n # Re-assign the current state and pad with zeroes\n current_state = format(xor_output | shift, '0{}b'.format(len(\n current_state)))\n","sub_path":"LFSR.py","file_name":"LFSR.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"77000877","text":"\"\"\"\nModule with a B+tree implementation.\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Generic\nfrom typing import Optional\nfrom typing import Tuple\n\nfrom pystrukts._types.basic import Endianness\nfrom pystrukts._types.basic import StrPath\nfrom pystrukts._types.comparable import KT\nfrom pystrukts._types.comparable import VT\nfrom pystrukts.trees.bplustree.memory import PagedFileMemory\nfrom pystrukts.trees.bplustree.node import BPTNode\nfrom pystrukts.trees.bplustree.node import InnerRecord\nfrom pystrukts.trees.bplustree.node import LeafRecord\nfrom pystrukts.trees.bplustree.serializers import DefaultSerializer\nfrom pystrukts.trees.bplustree.serializers import Serializer\nfrom pystrukts.trees.bplustree.settings import INNER_NODE_HEADERS_SPACE\nfrom pystrukts.trees.bplustree.settings import LEAF_NODES_HEADERS_SPACE\nfrom pystrukts.trees.bplustree.settings import NODE_POINTER_BYTE_SPACE\n\n\nclass BPlusTree(Generic[KT, VT]):\n \"\"\"\n Class that represents a B+tree.\n \"\"\"\n\n root: BPTNode[KT, VT]\n memory: PagedFileMemory\n inner_degree: int\n leaf_degree: int\n\n key_serializer: Serializer[KT]\n value_serializer: Serializer[VT]\n endianness: Endianness = \"big\"\n\n def __init__(\n self,\n tree_file: Optional[StrPath] = None,\n key_serializer: Optional[Serializer[KT]] = None,\n value_serializer: Optional[Serializer[VT]] = None,\n page_size: int = 4096,\n max_key_size: int = 8,\n max_value_size: int = 32,\n ) -> None:\n self.key_serializer = key_serializer if key_serializer is not None else DefaultSerializer[KT]()\n self.value_serializer = value_serializer if value_serializer is not None else DefaultSerializer[VT]()\n self.memory = PagedFileMemory(page_size, max_key_size, max_value_size, self.endianness, tree_file)\n self.inner_degree = self._compute_inner_degree()\n self.leaf_degree = self._compute_leaf_degree()\n\n if self.memory.is_new_file:\n self.root = self._create_root()\n else:\n self.root = self._read_root()\n\n def insert(self, key: KT, value: VT) -> None:\n \"\"\"\n Inserts a new key and value on the B+tree. Splits the root node or children nodes\n as the max number of keys are exceeded on the nodes according to the tree's degree.\n \"\"\"\n if self._is_full(self.root):\n old_root = self.root\n\n # new root is never a leaf node\n new_root = self._create_node(is_leaf=False)\n self.root = new_root\n self._swap_pages(old_root, new_root) # swap disk pages so that the new root stays on page 1\n\n # first node pointer is always created upon inner split\n new_root.first_node = old_root\n new_root.first_node_page = old_root.disk_page\n\n # splits the new root's child (old root) which is full to add the new key/value\n self._split_child(new_root, old_root, 0)\n self._insert_non_full(new_root, key, value)\n else:\n self._insert_non_full(self.root, key, value)\n\n def get(self, key: KT) -> Optional[VT]:\n \"\"\"\n Looks for a key on the B+tree. If it's not found, returns None.\n \"\"\"\n result = self._get(self.root, key)\n\n if result is not None:\n node, i = result # only leaf nodes can contain values, so we have a leaf node\n return node.leaf_records[i].value\n\n return None\n\n def _get(self, node: BPTNode[KT, VT], key: KT) -> Optional[Tuple[BPTNode[KT, VT], int]]:\n \"\"\"\n Finds a leaf node along with it's corresponding index int of its 'leaf_records' array\n containg the record with the value associated with the given key. If no such node is found,\n returns None.\n \"\"\"\n i = 0\n\n if node.is_leaf:\n while i < node.records_count and key > node.leaf_records[i].key:\n i += 1\n\n if i < node.records_count and key == node.leaf_records[i].key:\n return node, i\n\n return None\n\n # inner node searching\n while i < node.records_count and key > node.inner_records[i].key:\n i += 1\n\n # here we have an inner node, if i == 0, it's smaller than all keys\n # so look at the first child page (out of the inner_records)\n if i == 0:\n next_node_page = node.first_node_page\n next_node = node.first_node\n else:\n i -= 1 # [!]: key is bigger than first page keys, but inner_records starts at i == 0\n\n next_node_page = node.inner_records[i].next_node_page\n next_node = node.inner_records[i].next_node\n\n # check if the next inner node is in memory\n if next_node is not None:\n return self._get(next_node, key)\n\n # if not in memory, read it from disk and perform recursion\n return self._get(self._disk_read(next_node_page), key)\n\n def _disk_write(self, node: BPTNode[KT, VT]) -> None:\n \"\"\"\n Writes a given node to disk according to its page attribute by calling the memory allocator.\n \"\"\"\n node_page = node.disk_page\n node_data = node.to_page(\n self.memory.page_size, self.memory.max_key_size, self.memory.max_value_size, self.endianness\n )\n self.memory.write_page(node_page, node_data)\n\n def _disk_read(self, node_page: int) -> BPTNode[KT, VT]:\n \"\"\"\n Reads a given node from disk according to its page attribute by calling the memory allocator.\n \"\"\"\n page_data = self.memory.read_page(node_page)\n\n node_from_disk: BPTNode[KT, VT] = BPTNode(True, node_page, self.key_serializer, self.value_serializer)\n node_from_disk.load_from_page(page_data, self.memory.max_key_size, self.memory.max_value_size, self.endianness)\n\n return node_from_disk\n\n def _is_full(self, node: BPTNode[KT, VT]) -> bool:\n \"\"\"\n Checks if the given node is full of keys according to the tree's degree which takes\n into account the disk page sizes.\n \"\"\"\n degree = self.leaf_degree if node.is_leaf else self.inner_degree\n\n return node.records_count == 2 * degree - 1\n\n def _insert_non_full(self, node: BPTNode[KT, VT], key: KT, value: VT) -> None:\n \"\"\"\n Inserts a new key into a non-full node or raise an exception.\n \"\"\"\n # starts at the end of the inserted keys so far\n i = node.records_count - 1\n\n if node.is_leaf:\n new_record = LeafRecord(key, value)\n\n # finds final sorted position of the key (notice we need to do i + 1 after the loop)\n while i >= 0 and key < node.leaf_records[i].key:\n i -= 1\n\n # shift keys right to find a new spot for the new key\n node.leaf_records.insert(i + 1, new_record)\n\n self._disk_write(node)\n else:\n while i >= 0 and key < node.inner_records[i].key:\n i -= 1\n\n child_node_page = node.inner_records[i].next_node_page\n child_node = self._disk_read(child_node_page)\n node.inner_records[i].next_node = child_node\n\n if self._is_full(child_node):\n self._split_child(node, child_node, i)\n if key > node.inner_records[i].key:\n i += 1\n\n # as splitting adds a new key in the current node, refetch child\n child_node_page = node.inner_records[i].next_node_page\n child_node = self._disk_read(child_node_page)\n node.inner_records[i].next_node = child_node\n\n self._insert_non_full(child_node, key, value)\n\n def _split_child(self, parent_node: BPTNode[KT, VT], child_node: BPTNode[KT, VT], i: int) -> None:\n \"\"\"\n Splits the child according to whether it is a leaf or inner node. Notice that the parent node must\n be an inner node or it would not have children.\n \"\"\"\n if child_node.is_leaf:\n self._split_leaf_child(parent_node, child_node, i)\n else:\n self._split_inner_child(parent_node, child_node, i)\n\n def _split_inner_child(self, parent_node: BPTNode[KT, VT], child_node: BPTNode[KT, VT], i: int) -> None:\n \"\"\"\n Splits the i-th full child of the given parent node. Notice that the parent node, as it has a child, is\n an inner node (non-leaf) but the child itself can either be a leaf or an inner-node.\n \"\"\"\n new_node = self._create_node(is_leaf=False) # creates a new inner node\n degree = self.inner_degree\n\n # copies lower part of the full child node to the new node\n for j in range(0, degree - 1):\n record = child_node.inner_records[degree + j]\n new_node.inner_records.append(InnerRecord(record.key, record.next_node_page, record.next_node))\n\n # removes copied nodes from child node\n child_node.leaf_records.pop(degree + j)\n\n # inserts new key into the non-full inner node parent and make it point to the new node\n parent_node.inner_records.insert(\n i, InnerRecord(child_node.inner_records[degree - 1].key, new_node.disk_page, new_node)\n )\n child_node.inner_records.pop(degree - 1) # removes the split key from the child to 'pass' it to the parent\n\n # disk persistance of the split\n self._disk_write(child_node)\n self._disk_write(new_node)\n self._disk_write(parent_node)\n\n def _split_leaf_child(self, parent_node: BPTNode[KT, VT], child_node: BPTNode[KT, VT], i: int) -> None:\n \"\"\"\n Splits the i-th full child of the given parent node. Notice that the parent node, as it has a child, is\n an inner node and never a leaf node.\n \"\"\"\n new_node = self._create_node(is_leaf=True)\n degree = self.leaf_degree\n\n # copies lower part of the full child node to the new node\n for j in range(0, degree - 1):\n record = child_node.leaf_records[degree + j]\n new_node.leaf_records.append(LeafRecord(record.key, record.value))\n\n # removes copied nodes from child node\n child_node.leaf_records.pop(degree + j)\n\n # inserts new key into the non-full inner node parent and make it point to the new node\n parent_node.inner_records.insert(\n i, InnerRecord(child_node.leaf_records[degree - 1].key, new_node.disk_page, new_node)\n )\n\n # disk persistance of the split\n self._disk_write(child_node)\n self._disk_write(new_node)\n self._disk_write(parent_node)\n\n def _compute_inner_degree(self) -> int:\n \"\"\"\n Computes the degree (t) of the B+tree in order to use to decide when a given node is full or not. Here\n the degree of the tree is computed based on the amount of records that are able to fit a single disk page.\n\n Maximum allowed keys for any node: (2*t - 1) keys and 2*t children\n Minimum allowed keys for any node: (t - 1) keys and t children\n\n 2*t - 1 == \"max keys in node on a single page\" -> 2*t - 1 == free_page_size / each_record_size and solve for t\n \"\"\"\n page_headers_size = INNER_NODE_HEADERS_SPACE\n each_record_size = NODE_POINTER_BYTE_SPACE + self.memory.max_key_size\n free_page_size = self.memory.page_size - page_headers_size\n degree = int((free_page_size / each_record_size + 1) / 2) # max amount of keys in inner nodes\n\n if degree <= 0:\n raise ValueError(\n \"Impossible disk page memory layout for inner nodes: B+tree's degree <= 0! Please, \"\n \"increase the page size or reduce the max key value size.\"\n )\n\n return degree\n\n def _compute_leaf_degree(self) -> int:\n \"\"\"\n Computes the degree (t) of the B+tree for leaf nodes as their memory layout is different than inner nodes as\n key values take up more space. As a consequence, a leaf node becomes full with less records than an inner\n code and, as such, has a different degree.\n \"\"\"\n page_headers_size = LEAF_NODES_HEADERS_SPACE\n each_record_size = self.memory.max_key_size + self.memory.max_value_size\n free_page_size = self.memory.page_size - page_headers_size\n degree = int((free_page_size / each_record_size + 1) / 2)\n\n if degree <= 0:\n raise ValueError(\n \"Impossible disk page memory layout for leaf nodes: B+tree's degree <= 0! Please, \"\n \"increase the page size or reduce the max key value size.\"\n )\n\n return degree\n\n def _create_node(self, is_leaf: bool) -> BPTNode[KT, VT]:\n \"\"\"\n Allocates a new free disk page and instantiates a new node instance. The new node contains reference to\n its new disk page.\n \"\"\"\n new_page_number = self.memory.allocate_page()\n new_empty_node: BPTNode[KT, VT] = BPTNode(is_leaf, new_page_number, self.key_serializer, self.value_serializer)\n\n return new_empty_node\n\n def _swap_pages(self, node_1: BPTNode[KT, VT], node_2: BPTNode[KT, VT]) -> None:\n \"\"\"\n Swaps disk pages between two nodes. Notice that this mutates the two node's disk_page property.\n \"\"\"\n disk_page_1 = node_1.disk_page\n node_1.disk_page = node_2.disk_page\n node_2.disk_page = disk_page_1\n\n self._disk_write(node_1)\n self._disk_write(node_2)\n\n def _create_root(self) -> BPTNode[KT, VT]:\n \"\"\"\n Creates a new root for the B+tree (when the B+tree's file is new).\n \"\"\"\n page_number = self.memory.allocate_page()\n\n root = BPTNode(True, page_number, self.key_serializer, self.value_serializer)\n self._disk_write(root)\n\n return root\n\n def _read_root(self) -> BPTNode[KT, VT]:\n \"\"\"\n Reads a previous root of the B+tree from it's B+tree file.\n \"\"\"\n return self._disk_read(1) # root is always stored on page 1 (page 0 for tree metadata)\n","sub_path":"pystrukts/trees/bplustree/bplustree.py","file_name":"bplustree.py","file_ext":"py","file_size_in_byte":14013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"568359333","text":"import numpy as np\n\n#raiz de 2 está entre 1 y 2, se escoge un initial guess entre ellos\nx = 1.1\n\nn_max = 100\ni = 0\nwhile i < n_max:\n\n x_ant = x\n x = (x + 2/x)/2\n print(x)\n if x_ant == x:\n break\n i += 1\n","sub_path":"Python/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"167660250","text":"import global_config as G\nimport numpy as np\n\nfrom astropy.io import fits as pyfits\nfrom astropy.coordinates import Angle\nimport os.path as op\n\n#log = G.logging.getLogger('hetdex_logger')\n#log.setLevel(G.logging.DEBUG)\nlog = G.Global_Logger('hetdex_logger')\nlog.setlevel(G.logging.DEBUG)\n\nclass HetdexFits:\n '''A single HETDEX fits file ... 2D spectra, expected to be science file'''\n\n #needs open with basic validation\n #\n\n def __init__(self,fn,e_fn,fe_fn,dither_index=-1,panacea=False):\n self.okay = True\n self.filename = fn\n self.err_filename = e_fn\n self.fe_filename = fe_fn\n\n self.panacea = panacea\n\n self.tel_ra = None\n self.tel_dec = None\n self.parangle = None\n self.ifuid = None # reminder this is the cable\n self.ifuslot = None # reminder this is the position (slot) on the fplane\n self.side = None\n self.amp = None\n self.specid = None\n self.obs_date = None\n self.obs_ymd = None\n self.mjd = None\n self.obsid = None\n self.expid = None\n self.imagetype = None\n #self.exptime = None #don't need these right now\n #self.dettemp = None #don't need these right now\n\n self.data = None\n self.data_sky = None #sky NOT subtracted\n self.err_data = None\n self.fe_data = None #fiber extracted counts\n self.wave_data = None #matched wavelengths\n self.trace_data = None\n self.fiber_to_fiber = None\n self.error_analysis = None\n self.pixflat_data = None\n self.fiber_centers = None\n self.fe_crval1 = None\n self.fe_cdelt1 = None\n\n self.dither_index = dither_index\n\n #build basic info from filename\n\n #determine if 'cure'-style fits or panacea fits\n #stupid simple just for now\n #even for annulus, go ahead an read. Don't know if we are going to want the fits files, but may as well get them\n if \"multi_\" in self.filename: # example: multi_020_095_004_LU.fits\n self.read_panacea_fits()\n else:\n self.read_fits(use_cosmic_cleaned=G.PreferCosmicCleaned)\n self.read_efits(use_cosmic_cleaned=G.PreferCosmicCleaned)\n self.read_fefits()\n\n def read_fits(self,use_cosmic_cleaned=False):\n\n if not self.filename:\n return None\n\n if not op.exists(self.filename):\n log.error(\"Error. FITS file does not exist: \" + self.filename)\n return None\n\n try:\n f = pyfits.open(self.filename)\n except:\n log.error(\"could not open file \" + self.filename, exc_info=True)\n return None\n\n c = None\n try:\n if use_cosmic_cleaned:\n base = op.basename(self.filename)\n if base[0] != 'c':\n path = op.dirname(self.filename)\n\n cosmic = op.join(path,\"c\"+base)\n log.info(\"Attempting to open cosmic cleaned version of file: \" + cosmic)\n c = pyfits.open(cosmic)\n except:\n log.error(\"could not open file \" + cosmic, exc_info=True)\n c = None\n\n\n if c is not None:\n self.data = np.array(c[0].data)\n else:\n self.data = np.array(f[0].data)\n #clean up any NaNs\n self.data[np.isnan(self.data)] = 0.0\n\n try:\n self.tel_ra = float(Angle(f[0].header['TELRA']+\"h\").degree) #header is in hour::mm:ss.arcsec\n self.tel_dec = float(Angle(f[0].header['TELDEC']+\"d\").degree) #header is in deg:hh:mm:ss.arcsec\n self.parangle = f[0].header['PARANGLE']\n except:\n log.error(\"Cannot translate RA and/or Dec from FITS format to degrees in \" + self.filename, exc_info=True)\n\n try:\n self.ifuid = str(f[0].header['IFUID']).zfill(3)\n self.ifuslot = str(f[0].header['IFUSLOT']).zfill(3)\n self.side = f[0].header['CCDPOS']\n self.specid = str(f[0].header['SPECID']).zfill(3)\n self.obs_date = f[0].header['DATE-OBS']\n\n if '-' in self.obs_date: #expected format is YYYY-MM-DD\n self.obs_ymd = self.obs_date.replace('-','')\n self.mjd = f[0].header['MJD']\n self.obsid = f[0].header['OBSID']\n self.imagetype = f[0].header['IMAGETYP']\n #self.exptime = f[0].header['EXPTIME']\n #self.dettemp = f[0].header['DETTEMP']\n except:\n log.error(\"Cannot read expected keywords in fits header: \" + self.filename,exc_info=True)\n self.okay = False\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.filename, exc_info=True)\n\n if c is not None:\n try:\n c.close()\n except:\n log.error(\"could not close file cosmic file version of \" + self.filename, exc_info=True)\n return\n\n def read_efits(self,use_cosmic_cleaned=False):\n\n if self.err_filename is None:\n return None\n\n try:\n f = pyfits.open(self.err_filename)\n except:\n log.error(\"could not open file \" + self.err_filename, exc_info=True)\n return None\n\n c = None\n try:\n if use_cosmic_cleaned:\n #for simplicity, using self.filename instead of self.err_filename\n #since will assume err_filename = \"e.\" + self.filename\n base = op.basename(self.filename)\n if base[0] != 'c':\n path = op.dirname(self.err_filename)\n\n cosmic = op.join(path, \"e.c\" + base)\n log.info(\"Attempting to open cosmic cleaned version of file: \" + cosmic)\n c = pyfits.open(cosmic)\n except:\n log.error(\"could not open file \" + cosmic, exc_info=True)\n c = None\n\n if c is not None:\n self.err_data = np.array(c[0].data)\n else:\n self.err_data = np.array(f[0].data)\n\n # clean up any NaNs\n self.err_data[np.isnan(self.err_data)] = 0.0\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.err_filename, exc_info=True)\n\n if c is not None:\n try:\n c.close()\n except:\n log.error(\"could not close file cosmic file version of \" + self.filename, exc_info=True)\n\n return\n\n def read_fefits(self):\n\n if self.fe_filename is None:\n return None\n\n try:\n f = pyfits.open(self.fe_filename)\n except:\n log.error(\"could not open file \" + self.fe_filename, exc_info=True)\n return None\n\n try:\n self.fe_data = np.array(f[0].data)\n # clean up any NaNs\n self.fe_data[np.isnan(self.fe_data)] = 0.0\n self.fe_crval1 = f[0].header['CRVAL1']\n self.fe_cdelt1 = f[0].header['CDELT1']\n except:\n log.error(\"could not read values or data from file \" + self.fe_filename, exc_info=True)\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.fe_filename, exc_info=True)\n\n return\n\n def read_panacea_fits(self):\n #this represents one AMP\n #15+ hdus, different header keys\n\n if not self.filename:\n return None\n\n tarfile = None\n file = None\n if not op.exists(self.filename):\n # todo: try to find .tar file and load that way\n tar_fn = self.filename.split(\"/exp\")[0] + \".tar\"\n\n try:\n if op.exists(tar_fn):\n if tar.is_tarfile(tar_fn):\n tarfile = tar.open(name=tar_fn)\n\n #search for name first? or just try to extract it ... just extract ... if not there it will throw\n #an exception and it will be trapped\n #todo: if the naming of the path becomes irregular\n #todo: then substring search for the \"exp01/virus/multi_xxx.fits\" part (should still be exactly one match)\n #todo: and return the entire string in which it matches as the fits_fn\n #fqdn = tarfile.getnames() # list of all conents (as full paths) includes directories\n\n # remember, no leading '/' in tarfile contents\n # fits_fn = \"exp\" + self.filename.split(\"/exp\")[1]\n # i.e. = \"exp01/virus/multi_038_096_014_RU.fits\"\n\n fits_fn = \"virus\" + self.filename.split(\"/virus/virus\")[1]\n # ie. = \"virus0000001/exp01/virus/multi_038_096_014_RU.fits\"\n\n file = tarfile.extractfile(fits_fn)\n # remember do not close the tarfile until we are done\n else:\n log.info(\"Could not open tarfile:fits (%s: %s)\" %(tar_fn,fits_fn))\n\n except:\n log.error(\"Error. Could not open tarfile:fits (%s: %s)\" %(tar_fn,fits_fn), exc_info=True)\n tarfile = None\n file=None\n\n if file == None:\n log.error(\"Error. FITS file does not exist: \" + self.filename)\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n\n return None\n else:\n file = self.filename\n\n try:\n log.info(\"Loading %s ...\" %self.filename)\n f = pyfits.open(file) #file maybe a file name or a .tar file object\n except:\n log.error(\"could not open file \" + self.filename, exc_info=True)\n\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n return None\n\n try:\n #build idx\n #the position of each extention within the multi-frame panacea FITS is not fixed,\n #so need to build the index (dictionary) for each one we load\n hdu_idx = {}\n for i in range(len(f)):\n try:\n if f[i].header['EXTNAME'] in hdu_idx:\n log.warning(\"WARNING! Duplicate frame 'EXTNAME' found. ['%s'] at index %d and %d in file: %s\"\n %(f[i].header['EXTNAME'],hdu_idx[f[i].header['EXTNAME']], i,self.filename))\n else:\n hdu_idx[f[i].header['EXTNAME']] = i\n except:\n pass\n\n #use the cleaned image for display\n self.data = np.array(f[hdu_idx['clean_image']].data)\n self.data[np.isnan(self.data)] = 0.0 # clean up any NaNs\n\n if self.data.shape != (1032,1032):\n log.error(\"ERROR!! Unexpected data shape for [clean_image]. Expected (1032,1032), got (%d,%d)\" %(self.data.shape))\n\n #with the sky NOT subtracted\n try:\n self.data_sky = np.array(f[0].data)\n self.data_sky[np.isnan(self.data_sky)] = 0.0 # clean up any NaNs\n except: #error, but not fatal, just keep going\n log.error(\"Could not load sky NOT subtracted fits data from multi*fits\")\n\n if self.data_sky.shape != (1032,1032):\n log.error(\"ERROR!! Unexpected data shape for [0] (data_sky). Expected (1032,1032), got (%d,%d)\"\n %(self.data_sky.shape))\n\n\n #get error equivalent\n self.err_data = np.array(f[hdu_idx['error']].data)\n if self.err_data.shape != (1032, 1032):\n print(\"TEMPORARY!!! using [1] for ['error'] frame until name correctd.\")\n self.err_data = np.array(f[1].data)\n\n self.err_data[np.isnan(self.err_data)] = 0.0\n if self.err_data.shape != (1032,1032):\n log.error(\"ERROR!! Unexpected data shape for [error]. Expected (1032,1032), got (%d,%d)\"\n %(self.err_data.shape))\n\n #get fe equivalent\n self.fe_data = np.array(f[hdu_idx['sky_subtracted']].data)\n self.fe_data[np.isnan(self.fe_data)] = 0.0\n if self.fe_data.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [sky_subtracted]. Expected (112,1032), got (%d,%d)\"\n %(self.fe_data.shape))\n\n # get fe equivalent (need also the matching wavelengths)\n self.wave_data = np.array(f[hdu_idx['wavelength']].data)\n self.wave_data[np.isnan(self.wave_data)] = 0.0\n if self.wave_data.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [wavelength]. Expected (112,1032), got (%d,%d)\"\n %(self.wave_data.shape))\n\n self.trace_data = np.array(f[hdu_idx['trace']].data)\n self.trace_data[np.isnan(self.trace_data)] = 0.0\n if self.trace_data.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [trace]. Expected (112,1032), got (%d,%d)\"\n %(self.trace_data.shape))\n\n self.fiber_to_fiber = np.array(f[hdu_idx['fiber_to_fiber']].data)\n self.fiber_to_fiber[np.isnan(self.fiber_to_fiber)]\n if self.fiber_to_fiber.shape != (112,1032):\n log.error(\"ERROR!! Unexpected data shape for [fiber_to_fiber]. Expected (112,1032), got (%d,%d)\"\n %(self.fiber_to_fiber.shape))\n\n #[0] = wavelength, [1] = empirical? [2] = expected or estimated?\n self.error_analysis = np.array(f[hdu_idx['error_analysis']].data)\n self.error_analysis[np.isnan(self.error_analysis)]\n if self.error_analysis.shape != (3,512):\n log.error(\"ERROR!! Unexpected data shape for [error_analysis]. Expected (3,512), got (%d,%d)\"\n %(self.error_analysis.shape))\n\n #note: (this is done by IFU in build_fibers for each fiber that is constructed)\n #closest thing to error is the error_analysis * fiber_to_fiber (for the fiber in question)\n #take spectra (\"clean image\") and divide by fiber_to_fiber for the fiber in question\n #note fiber to fiber is the deviation from the average of fibers\n #when getting the data for a fiber, need to interpolate the error_analysis to be on same grid\n # as the wave_data for that fiber and then do the multiply and divide as needed\n\n\n # get fiber centers\n # the fits representation is backward (with grid x,y: 1,112 and 2,112 (i.e at the top) == fiber 1))\n self.fiber_centers = np.array(f[hdu_idx['ifupos']].data)\n if self.fiber_centers.shape != (112, 2):\n log.error(\"ERROR!! Unexpected data shape for [ifupos]. Expected (112,2), got (%d,%d)\"\n % (self.fiber_centers.shape))\n\n #self.pixflat_data = np.array(f[hdu_idx['flat_image']].data)\n #self.pixflat_data[np.isnan(self.pixflat_data)] = 0.0\n\n self.panacea = True\n\n #most complete header in the raw image\n #todo: at some point in late 2017, the 'image' header was dropped ... as this becomes common,\n #todo: should stop trying to read the 'image' header and just always assume the 0th is PRIMARY?\n #todo: (is always TRUE ... or at least always after a re-reduction?)\n try:\n idx = hdu_idx['image']\n except:\n log.debug(\"[image] header not found. Will assume 0th header is the PRIMARY.\")\n idx = 0\n\n except:\n log.error(\"Cannot read fits header. Missing expected keywords. \" + self.filename, exc_info=True)\n self.okay = False\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n return\n\n try:\n self.tel_ra = float(f[idx].header['RA']) * 15.0 # header is in decimal hours\n self.tel_dec = float(f[idx].header['DEC']) # header is in decimal degs\n self.parangle = f[idx].header['PA']\n except:\n log.error(\"Non-fatal: Cannot translate RA and/or Dec from FITS format to degrees in \" + self.filename, exc_info=True)\n #might be okay, depeding on if the individual emission lines have the weighted RA and Dec Specified\n\n try:\n self.ifuid = str(f[idx].header['IFUSID']).zfill(3)\n self.ifuslot = str(f[idx].header['IFUSLOT']).zfill(3)\n self.specid = str(f[idx].header['SPECID']).zfill(3)\n self.amp = f[idx].header['AMP']\n self.side = f[idx].header['AMP'][0] #the L or R ... probably don't need this anyway\n #self.exptime = f[idx].header['EXPTIME']\n except:\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n\n log.error(\"Cannot read fits header. Missing expected keywords. Will attempt to pull from filename.\" + self.filename, exc_info=True)\n #try to get info from the filename\n self.parse_panacea_fits_name(self.filename)\n return\n\n try:\n if tarfile:\n tarfile.close()\n except:\n log.error(\"could not close tar file \", exc_info=True)\n\n try:\n f.close()\n except:\n log.error(\"could not close file \" + self.filename, exc_info=True)\n\n return\n\n def parse_panacea_fits_name(self,name):\n if name is not None:\n if \"multi_\" in name: #multi_037_073_031_LL.fits\n toks = name.split(\"_\") #multi_fits_basename = \"multi_\" + self.specid + \"_\" + self.ifu_slot_id + \"_\" + self.ifu_id + \"_\"\n if len(toks) == 5:\n try:\n self.specid = toks[1].zfill(3)\n self.ifuslot = toks[2].zfill(3)\n self.ifuid = toks[3].zfill(3)\n self.amp = toks[4][0:2]\n self.side =toks[4][0]\n except:\n log.error(\"Cannot parse panaces fits filename: %s\" %name,exc_info=True)\n self.okay = False\n\n\n\n def cleanup(self):\n #todo: close fits handles, etc\n pass\n\n","sub_path":"hetdex_fits.py","file_name":"hetdex_fits.py","file_ext":"py","file_size_in_byte":18623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"396920325","text":"\n\nfrom xai.brain.wordbase.nouns._alliteration import _ALLITERATION\n\n#calss header\nclass _ALLITERATIONS(_ALLITERATION, ):\n\tdef __init__(self,): \n\t\t_ALLITERATION.__init__(self)\n\t\tself.name = \"ALLITERATIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"alliteration\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_alliterations.py","file_name":"_alliterations.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"300425488","text":"\"\"\"\nFunctions that aid definition of fourier transform processing.\n\"\"\"\n\nimport astropy.constants as constants\n\nfrom arl.data.data_models import *\nfrom arl.data.parameters import *\nfrom arl.fourier_transforms.convolutional_gridding import anti_aliasing_calculate, w_kernel\nfrom arl.image.iterators import *\n\nlog = logging.getLogger(__name__)\n\n\ndef get_frequency_map(vis, im=None, **kwargs):\n \"\"\" Map channels from visibilities to image\n\n \"\"\"\n \n # Find the unique frequencies in the visibility\n ufrequency = numpy.unique(vis.frequency)\n vnchan = len(ufrequency)\n\n if im is None:\n spectral_mode = 'channel'\n vfrequencymap = get_rowmap(vis.frequency, ufrequency)\n assert min(vfrequencymap) >= 0, \"Invalid frequency map: visibility channel < 0\"\n\n\n elif im.data.shape[0] == 1 and vnchan >= 1:\n spectral_mode = 'mfs'\n vfrequencymap = numpy.zeros_like(vis.frequency, dtype='int')\n\n else:\n # We can map these to image channels\n v2im_map = im.wcs.sub(['spectral']).wcs_world2pix(ufrequency, 0)[0].astype('int')\n \n spectral_mode = 'channel'\n nrows = len(vis.frequency)\n row2vis = numpy.array(get_rowmap(vis.frequency, ufrequency))\n vfrequencymap = [v2im_map[row2vis[row]] for row in range(nrows)]\n \n assert min(vfrequencymap) >= 0, \"Invalid frequency map: image channel < 0\"\n assert max(vfrequencymap) < im.shape[0], \"Invalid frequency map: image channel > number image channels\"\n \n return spectral_mode, vfrequencymap\n\n\ndef get_polarisation_map(vis: Visibility, im: Image=None, **kwargs):\n \"\"\" Get the mapping of visibility polarisations to image polarisations\n \n \"\"\"\n if vis.polarisation_frame == im.polarisation_frame:\n if vis.polarisation_frame == PolarisationFrame('stokesI'):\n return \"stokesI->stokesI\", lambda pol: 0\n elif vis.polarisation_frame == PolarisationFrame('stokesIQUV'):\n return \"stokesIQUV->stokesIQUV\", lambda pol: pol\n\n return \"unknown\", lambda pol: pol\n\n\ndef get_rowmap(col, ucol=None):\n \"\"\" Map to unique cols\n \n :param col: Data column\n :param ucol: Unique values in col\n \"\"\"\n pdict = {}\n \n def phash(f):\n return numpy.round(f).astype('int')\n \n if ucol is None:\n ucol = numpy.unique(col)\n \n for i, f in enumerate(ucol):\n pdict[phash(f)] = i\n vmap = []\n for p in col:\n vmap.append(pdict[phash(p)])\n\n return vmap\n\n\ndef get_uvw_map(vis, im, **kwargs):\n \"\"\" Get the generators that map channels uvw to pixels\n\n \"\"\"\n # Transform parameters\n padding = get_parameter(kwargs, \"padding\", 2)\n \n # Model image information\n inchan, inpol, ny, nx = im.data.shape\n shape = (1, int(round(padding * ny)), int(round(padding * nx)))\n # UV sampling information\n uvwscale = numpy.zeros([3])\n uvwscale[0:2] = im.wcs.wcs.cdelt[0:2] * numpy.pi / 180.0\n assert uvwscale[0] != 0.0, \"Error in uv scaling\"\n fov = int(round(padding * nx)) * numpy.abs(uvwscale[0])\n \n vuvwmap = uvwscale * vis.uvw\n uvw_mode = \"2d\"\n \n return uvw_mode, shape, padding, vuvwmap\n\n\ndef standard_kernel_list(vis, shape, oversampling=8, support=3):\n \"\"\"Return a lambda function to calculate the standard visibility kernel\n\n :param vis: visibility\n :param shape: tuple with 2D shape of grid\n :param oversampling: Oversampling factor\n :param support: Support of kernel\n :returns: Function to look up gridding kernel\n \"\"\"\n return [anti_aliasing_calculate(shape, oversampling, support)[1]]\n\n\ndef w_kernel_list(vis, shape, fov, oversampling=4, wstep=100.0, npixel_kernel=16):\n \"\"\"Return a generator for the w kernel for each row\n\n This function is called once. It uses an LRU cache to hold the convolution kernels. As a result,\n initially progress is slow as the cache is filled. Then it speeds up.\n\n :param vis: visibility\n :param shape: tuple with 2D shape of grid\n :param fov: Field of view in radians\n :param oversampling: Oversampling factor\n :param wstep: Step in w between cached functions\n :returns: Function to look up gridding kernel as function of row, and cache\n \"\"\"\n wmax = numpy.max(numpy.abs(vis.w))\n log.debug(\"w_kernel_list: Maximum w = %.1f , step is %.1f wavelengths\" % (wmax, wstep))\n \n def digitise_w(w):\n return numpy.round(w / wstep).astype('int')\n \n # Use a dictionary but look at performance\n kernels = {}\n wint_list = numpy.unique(digitise_w(vis.w))\n for wint in wint_list:\n kernels[wint] = w_kernel(field_of_view=fov, w=wstep * wint, npixel_farfield=shape[0],\n npixel_kernel=npixel_kernel, kernel_oversampling=oversampling)\n # We will return a generator that can be instantiated at the last moment. The memory for\n # the kernels is needed but the pointer per row can be deferred.\n w_kernels = (kernels[digitise_w(w)] for w in vis.w)\n \n return w_kernels\n\n\ndef get_kernel_list(vis: Visibility, im, **kwargs):\n \"\"\"Get the list of kernels, one per visibility\n \n \"\"\"\n \n shape = im.data.shape\n npixel = shape[3]\n cellsize = numpy.pi * im.wcs.wcs.cdelt[1] / 180.0\n \n kernelname = get_parameter(kwargs, \"kernel\", \"2d\")\n oversampling = get_parameter(kwargs, \"oversampling\", 8)\n padding = get_parameter(kwargs, \"padding\", 2)\n \n gcf, _ = anti_aliasing_calculate((padding * npixel, padding * npixel), oversampling)\n\n wabsmax = numpy.max(numpy.abs(vis.w))\n if kernelname == 'wprojection' and wabsmax > 0.0:\n \n # wprojection needs a lot of commentary!\n log.debug(\"get_kernel_list: Using wprojection kernel\")\n \n # The field of view must be as padded!\n fov = cellsize * npixel * padding\n r_f = (cellsize * npixel / 2) ** 2 / abs(cellsize)\n log.debug(\"get_kernel_list: Fresnel number = %f\" % (r_f))\n delA = get_parameter(kwargs, 'wloss', 0.02)\n \n advice = advise_wide_field(vis, delA)\n wstep = get_parameter(kwargs, \"wstep\", advice['w_sampling_primary_beam'])\n \n log.debug(\"get_kernel_list: Using w projection with wstep = %f\" % (wstep))\n \n # Now calculate the maximum support for the w kernel\n npixel_kernel = get_parameter(kwargs, \"kernelwidth\", (2 * int(round(numpy.sin(0.5 * fov) * npixel/4.0))))\n assert npixel_kernel % 2 == 0\n log.debug(\"get_kernel_list: Maximum w kernel full width = %d pixels\" % (npixel_kernel))\n kernel_list = w_kernel_list(vis, (npixel, npixel), fov, wstep=wstep,\n npixel_kernel=npixel_kernel, oversampling=oversampling)\n else:\n kernelname = '2d'\n kernel_list = standard_kernel_list(vis, (padding * npixel, padding * npixel), oversampling=8, support=3)\n \n return kernelname, gcf, kernel_list\n\ndef advise_wide_field(vis, delA=0.02, oversampling_synthesised_beam=3.0, guard_band_image=6.0, facets=1.0):\n \"\"\" Advise on parameters for wide field imaging.\n \n For example::\n \n advice = advise_wide_field(vis, delA)\n wstep = get_parameter(kwargs, \"wstep\", advice['w_sampling_primary_beam'])\n\n \n :param vis:\n :param delA: Allowed coherence loss (def: 0.02)\n :param oversampling_synthesised_beam: Oversampling of the synthesized beam (def: 3.0)\n :param guard_band_image: Number of primary beam half-widths-to-half-maximum to image (def: 6)\n :returns: dict of advice\n \"\"\"\n maximum_baseline = numpy.max(numpy.abs(vis.uvw)) # Wavelengths\n log.info(\"advise_wide_field: Maximum baseline %.1f (wavelengths)\" % (maximum_baseline))\n \n diameter = numpy.min(vis.configuration.diameter)\n log.info(\"advise_wide_field: Station/antenna diameter %.1f (meters)\" % (diameter))\n\n wavelength = constants.c.to('m/s').value / numpy.min(vis.frequency)\n log.info(\"advise_wide_field: Maximum wavelength %.3f (meters)\" %(wavelength))\n\n primary_beam_fov = wavelength / diameter\n log.info(\"advise_wide_field: Primary beam %s\" % (rad_and_deg(primary_beam_fov)))\n\n image_fov = primary_beam_fov * guard_band_image\n log.info(\"advise_wide_field: Image field of view %s\" % (rad_and_deg(image_fov)))\n\n facet_fov = primary_beam_fov * guard_band_image / facets\n log.info(\"advise_wide_field: Facet field of view %s\" % (rad_and_deg(facet_fov)))\n\n synthesized_beam = 1.0 / (maximum_baseline)\n log.info(\"advise_wide_field: Synthesized beam %s\" % (rad_and_deg(synthesized_beam)))\n\n cellsize = synthesized_beam/oversampling_synthesised_beam\n log.info(\"advise_wide_field: Cellsize %s\" % (rad_and_deg(cellsize)))\n\n npixels = int(round(image_fov/cellsize))\n log.info(\"advice_wide_field: Npixels per side = %d\" % (npixels))\n\n # Following equation is from Cornwell, Humphreys, and Voronkov (2012) (equation 24)\n # We will assume that the constraint holds at one quarter the entire FOV i.e. that\n # the full field of view includes the entire primary beam\n\n w_sampling_image = numpy.sqrt(2.0 * delA) / (numpy.pi * image_fov ** 2)\n log.info(\"advice_wide_field: W sampling for full image = %.1f (wavelengths)\" % (w_sampling_image))\n\n w_sampling_facet = numpy.sqrt(2.0 * delA) / (numpy.pi * facet_fov ** 2)\n log.info(\"advice_wide_field: W sampling for facet = %.1f (wavelengths)\" % (w_sampling_image))\n\n w_sampling_primary_beam = numpy.sqrt(2.0 * delA) / (numpy.pi * primary_beam_fov ** 2)\n log.info(\"advice_wide_field: W sampling for primary beam = %.1f (wavelengths)\" % (w_sampling_primary_beam))\n\n time_sampling_image = 86400.0 * w_sampling_image / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Time sampling for full image = %.1f (s)\" % (time_sampling_image))\n\n time_sampling_facet = 86400.0 * w_sampling_facet / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Time sampling for facet = %.1f (s)\" % (time_sampling_facet))\n\n time_sampling_primary_beam = 86400.0 * w_sampling_primary_beam / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Time sampling for primary beam = %.1f (s)\" % (time_sampling_primary_beam))\n\n freq_sampling_image = numpy.max(vis.frequency) * w_sampling_image / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Frequency sampling for full image = %.1f (Hz)\" % (freq_sampling_image))\n\n freq_sampling_facet = numpy.max(vis.frequency) * w_sampling_facet / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Frequency sampling for facet = %.1f (Hz)\" % (freq_sampling_facet))\n\n freq_sampling_primary_beam = numpy.max(vis.frequency) * w_sampling_primary_beam / (numpy.pi * maximum_baseline)\n log.info(\"advice_wide_field: Frequency sampling for primary beam = %.1f (Hz)\" % (freq_sampling_primary_beam))\n\n return locals()\n\ndef rad_and_deg(x):\n \"\"\" Stringify x in radian and degress forms\n \n \"\"\"\n return \"%.6f (rad) %.3f (deg)\" % (x, 180.0 * x / numpy.pi)\n\n","sub_path":"arl/fourier_transforms/ftprocessor_params.py","file_name":"ftprocessor_params.py","file_ext":"py","file_size_in_byte":10950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"550558852","text":"t=int(input())\nfor test in range(t):\n string, S = input().split()\n S = int(S)\n A = [int(i) for i in string]\n length = len(A)\n array = [0] * (length + 1)\n summm = total = 0\n\n for i in range(length):\n summm += A[i]\n if summm >= S:\n total += array[summm - S]\n if summm == S:\n total += 1\n array[summm] += 1\n print(total)","sub_path":"Code/CodeRecords/2617/60785/276684.py","file_name":"276684.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"119544928","text":"# encoding: utf-8\n\nimport os\nfrom gvsig.libs.formpanel import FormPanel\nfrom javax.swing.table import DefaultTableModel\nfrom javax.swing import JTable\nfrom javax.swing import SwingConstants\nfrom org.gvsig.app import ApplicationLocator\nfrom gvsig import commonsdialog\nfrom studentscreator import StudentsCreatorPanel\nfrom studentsupdater import StudentsUpdaterPanel\nfrom studentsdeleter import StudentsDeleterPanel\n\nclass StudentsEditorPanel(FormPanel):\n \n def __init__(self):\n FormPanel.__init__(self, os.path.join(os.path.dirname(__file__), \"studentseditor.xml\"))\n self.setPreferredSize(646, 285)\n tableModel = DefaultTableModel(0, 3)\n self.tableStudents.setModel(tableModel)\n self.tableStudents.getColumnModel().getColumn(0).setHeaderValue(\"Id\")\n self.tableStudents.getColumnModel().getColumn(0).setPreferredWidth(154)\n self.tableStudents.getColumnModel().getColumn(1).setHeaderValue(\"Password\")\n self.tableStudents.getColumnModel().getColumn(1).setPreferredWidth(154)\n self.tableStudents.getColumnModel().getColumn(2).setHeaderValue(\"Name\")\n self.tableStudents.getColumnModel().getColumn(2).setPreferredWidth(305)\n self.tableStudents.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)\n self.tableStudents.getTableHeader().getDefaultRenderer().setHorizontalAlignment(SwingConstants.CENTER)\n self.tableStudents.getTableHeader().setResizingAllowed(0)\n self.tableStudents.getTableHeader().setReorderingAllowed(0)\n self.loadStudents()\n \n def btnCreate_click(self, *args):\n create = commonsdialog.confirmDialog(\"Do you want to create students?\", \"Create\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if create == 0:\n studentsCreatorPanel = StudentsCreatorPanel()\n studentsCreatorPanel.showWindow(\"Create\")\n \n def btnUpdate_click(self, *args):\n rowCount = self.tableStudents.getRowCount()\n if rowCount != 0:\n update = commonsdialog.confirmDialog(\"Do you want to update students?\", \"Update\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if update == 0:\n studentsUpdaterPanel = StudentsUpdaterPanel()\n studentsUpdaterPanel.showWindow(\"Update\")\n else:\n commonsdialog.msgbox(\"Zero students!\", \"Update\", commonsdialog.IDEA)\n \n def btnDelete_click(self, *args):\n rowCount = self.tableStudents.getRowCount()\n if rowCount != 0:\n delete = commonsdialog.confirmDialog(\"Do you want to delete students?\", \"Delete\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if delete == 0:\n studentsDeleterPanel = StudentsDeleterPanel()\n studentsDeleterPanel.showWindow(\"Delete\")\n else:\n commonsdialog.msgbox(\"Zero students!\", \"Delete\", commonsdialog.IDEA)\n \n def btnExit_click(self, *args):\n exit = commonsdialog.confirmDialog(\"Do you want to exit?\", \"Exit\", commonsdialog.YES_NO, commonsdialog.QUESTION)\n if exit == 0:\n self.hide()\n \n def loadStudents(self):\n studentsFilePath = os.path.join(os.path.dirname(__file__), \"..\", \"data\", \"students.dbf\")\n store = self.loadDbf(studentsFilePath)\n features = store.features()\n tableModel = self.tableStudents.getModel()\n for feature in features:\n row = [feature.get(\"ID\"), feature.get(\"PASSWORD\"), feature.get(\"NAME\")]\n tableModel.addRow(row)\n features.dispose()\n store.dispose()\n \n @staticmethod\n def loadDbf(dbfFilePath):\n manager = ApplicationLocator.getManager()\n datamanager = manager.getDataManager()\n storeparameters = datamanager.createStoreParameters(\"DBF\")\n storeparameters.setDynValue(\"DbfFile\", dbfFilePath)\n store = datamanager.openStore(\"DBF\", storeparameters)\n return store\n\ndef main(*args):\n pass\n '''\n # testing\n studentsEditorPanel = StudentsEditorPanel()\n studentsEditorPanel.showWindow(\"Testing panel\")\n '''","sub_path":"GSoC_2017/EducationalGames/Games/editors/studentseditor.py","file_name":"studentseditor.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"227185992","text":"from collections import namedtuple\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport pdb\n\nfrom parse_path import constituency_path, dependency_path\ndp = dependency_path()\ncp = constituency_path()\ndef convert_mask_index(masks):\n '''\n Find the indice of none zeros values in masks, namely the target indice\n '''\n target_indice = []\n for mask in masks:\n indice = torch.nonzero(mask == 1).squeeze(1).cpu().numpy()\n target_indice.append(indice)\n return target_indice\n\ndef get_dependency_weight(tokens, targets, max_len):\n '''\n Dependency weight\n tokens: texts\n max_len: max length of texts\n '''\n weights = np.zeros([len(tokens), max_len])\n for i, token in enumerate(tokens):\n try:\n graph = dp.build_graph(token)\n mat = dp.compute_node_distance(graph, max_len)\n except:\n print('Error!!!!!!!!!!!!!!!!!!')\n print(text)\n\n try:\n max_w, _, _ = dp.compute_soft_targets_weights(mat, targets[i])\n weights[i, :len(max_w)] = max_w\n except:\n print('text process error')\n print(text, targets[i])\n break\n return weights\n\ndef get_context_weight(texts, targets, max_len):\n '''\n Constituency weight\n '''\n weights = np.zeros([len(texts), max_len])\n for i, token in enumerate(texts):\n #print('Original word num')\n #print(len(token))\n #text = ' '.join(token)#Connect them into a string\n #stanford nlp cannot identify the abbreviations ending with '.' in the sentences\n\n try:\n max_w, min_w, a_v = cp.proceed(token, targets[i])\n weights[i, :len(max_w)] = max_w\n except Exception as e:\n print(e)\n print(token, targets[i])\n return weights\n\ndef get_target_emb(sent_vec, masks, is_average=True):\n '''\n '''\n batch_size, max_len, embed_dim = sent_vec.size()\n masks = masks.type_as(sent_vec)\n masks = masks.expand(embed_dim, batch_size, max_len)\n masks = masks.transpose(0, 1).transpose(1, 2)#The same size as sentence vector\n target_emb = sent_vec * masks\n if is_average:\n target_emb_avg = torch.sum(target_emb, 1)/torch.sum(masks, 1)#Batch_size*embedding\n return target_emb_avg\n return target_emb\n\ndef to_scalar(var):\n # returns a python float\n return var.view(-1).data.tolist()[0]\n\ndef argmax(vec):\n # vec is only 1d vec\n # return the argmax as a python int\n _, idx = torch.max(vec, 0)\n return to_scalar(idx)\n\n# the input is 2d dim tensor\n# output 1d tensor\ndef argmax_m(mat):\n ret_v, ret_ind = [], []\n m, n = mat.size()\n for i in range(m):\n ind_ = argmax(mat[i])\n ret_ind.append(ind_)\n ret_v.append(mat[i][ind_])\n if type(ret_v[0]) == Variable or type(ret_v[0]) == torch.Tensor:\n return ret_ind, torch.stack(ret_v)\n else:\n return ret_ind, torch.Tensor(ret_v)\n\n# Compute log sum exp in a numerically stable way for the forward algorithm\n# vec is n * n, norm in row\ndef log_sum_exp_m(mat):\n row, column = mat.size()\n ret_l = []\n for i in range(row):\n vec = mat[i]\n max_score = vec[argmax(vec)]\n max_score_broadcast = max_score.view( -1).expand(1, vec.size()[0])\n ret_l.append( max_score + \\\n torch.log(torch.sum(torch.exp(vec - max_score_broadcast))))\n return torch.stack(ret_l)\n\ndef log_sum_exp(vec_list):\n tmp_mat = torch.stack(vec_list, 0)\n m,n = tmp_mat.size()\n # value may be nan because of gradient explosion\n try:\n max_score = torch.max(tmp_mat)\n except:\n pdb.set_trace()\n max_expand = max_score.expand(m, n)\n max_ex_v = max_score.expand(1, n)\n # sum along dim 0\n ret_val = max_ex_v + torch.log(torch.sum(torch.exp(tmp_mat - max_expand), 0))\n return ret_val\n\n# vec1 and vec2 both 1d tensor\n# return 1d tensor\ndef add_broad(vec1, vec2):\n s_ = vec1.size()[0]\n vec1 = vec1.expand(3, s_).transpose(0,1)\n vec2 = vec2.expand(s_, 3)\n new_vec = vec1 + vec2\n return new_vec.view(-1)\n\n# transform a list to 1d vec\ndef to_1d(vec_list):\n ret_v = vec_list[0].clone()\n v_l = len(vec_list)\n for i in range(1, v_l):\n ret_v = add_broad(ret_v, vec_list[i])\n return ret_v\n\ndef to_ind(num, logit):\n ret_l = []\n for i in reversed(range(logit)):\n tmp = num / 3 ** i\n num = num - tmp * 3 ** i\n ret_l.append(tmp)\n return list(reversed(ret_l))\n\ndef create_empty_var(if_gpu):\n if if_gpu:\n loss = Variable(torch.Tensor([0]).cuda())\n else:\n loss = Variable(torch.Tensor([0])) \n return loss","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"253680965","text":"# -*- coding: utf-8 -*-\nfrom distutils.core import setup\nfrom setuptools import find_packages\n\nwith open('docs/requirements.txt') as f:\n required = f.read().splitlines()\n\nsetup(\n name='tango-happenings',\n version='0.7.2',\n author=u'Tim Baxter',\n author_email='mail.baxter@gmail.com',\n url='https://github.com/tBaxter/django-happenings',\n license='LICENSE',\n description='Reusable Django events and calendaring.',\n long_description=open('README.md').read(),\n packages=find_packages(),\n install_requires=required,\n zip_safe=False,\n include_package_data=True,\n dependency_links = [\n 'http://github.com/tBaxter/vobject/tarball/master#egg=vobject',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"434850776","text":"\"\"\"\n filename: bieberhash.py\n problem: using hash tables and handling collisions\n author: Elijah Kliot\ndescription: reads a .txt file with patron names and tabs and then\n populates a hash table corresponding to their seats\n and tab amounts\n\"\"\"\n\nfrom hashtable import *\n\ndef create_bills( file, cap ):\n \"\"\"\n simulates the seating and billing of concert patrons\n using a hash table\n\n file -- .txt to be read with patron names and tabs in format:\n {str} ${int}\n cap -- the maximum seating capacity of the concert\n\n returns None\n \"\"\"\n cap = int( cap )\n bills = createHashTable( cap )\n txt = open( file )\n print( \"YARR, WELCOME.\\n\" )\n \n for line in txt:\n s = line.split()\n name = s[ 0 ]\n tab = int( s[ 1 ][ 1:: ] )\n\n if bills.size > cap:\n print( \"THAR BE NOT ENOUGH SEATS, CAP'N\" )\n quit()\n\n if has( bills, name ):\n print( \"FOUND YA,\", name + \", AT SEAT NUMBER\", indexOf( bills, name ) )\n cur = get( bills, name )\n print( \"YA GOT\", cur, \"DUBLOONS ON YER TAB\" )\n print( \"AND NOW YA GOT\", tab, \"MORE, FER A TOTAL OF\",\n ( cur + tab ), \"DUBLOONS\\n\" )\n put( bills, name, cur + tab )\n\n else:\n print( name + \", YER PRIMARY SEAT NUMBER BE\", primHash( name, cap ),\n \"AND YER SECONDARY SEAT NUMBER BE\", secHash( name, cap ) )\n\n if bills.table[ primHash( name, cap ) ] == None:\n put( bills, name, tab )\n print( \"YA'VE BEEN SEATED,\", name + \", AT SEAT NUMBER\",\n indexOf( bills, name ), \"AND YER TAB IS FER\", tab, \"DUBLOONS\\n\" )\n\n else:\n seat = primHash( name, cap )\n occu = bills.table[ seat ].key\n print( \"IT SEEMS YER PRIMARY SEAT,\", str( seat ) + \", AIN'T VACANT,\",\n name + \". \\nWE'LL BE BOOTIN'\", occu, \"TA THEIR SECONDARY SEAT AT SEAT\",\n str( secHash( occu, cap ) ) + \". \\nMEANWHILE, TAKE A SEAT AT\",\n str( seat ), \"AND YER TAB IS\", tab, \"DUBLOONS.\\n\" )\n put( bills, name, tab )\n\n print( \"\\n++++++\\nYARR HARR FIDDLE DEE DEE\\nDO WHAT YA WANT 'CAUSE A PIRATE IS FREE\\n++++++\",\n \"\\n\\n\\nTH' CONCERT IS OVER, ALL YOU BETTER PAY YER TABS.\" )\n print( \"NOW LET'S SEE WHO OWES WOT:\\n\" )\n\n for pat in bills.table:\n if pat != None:\n name = pat.key\n seat = indexOf( bills, name )\n tab = pat.value\n print( name + \", YER IN SEAT NUMBER\", seat, \"AND YA OWE\", tab, \"DUBLOONS\" )\n\n print( \"\\nNOW GET OUT, YA BARNACLE-LICKING MONGRELS\\n\\n\\n\" )\n print( HashTableToStr( bills ) ) #plain-ish english output\n\ndef main():\n \"\"\"\n prompts for concert seating capacity and text file\n then runs simulation\n\n returns None\n \"\"\"\n size = input( \"Size of hash table: \" )\n## size = 100\n file = input( \"Filename: \" )\n## file = \"test.txt\"\n create_bills( file, size )\n\nmain()\n","sub_path":"Labs/LabI [100]/bieberhash.py","file_name":"bieberhash.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"306722471","text":"# %load tmax.py\r\nimport os\r\nfrom matplotlib import pyplot as plt\r\nimport cv2\r\nimport numpy as np\r\nfrom scipy.linalg import circulant\r\nfrom scipy.linalg import solve\r\nfrom scipy import signal\r\nfrom BaselineRemoval import BaselineRemoval\r\nimport copy\r\nfrom scipy.signal import find_peaks\r\nfrom skimage import data, filters\r\nfrom skimage import transform, exposure\r\n\r\n\r\n# Compute IRF:\r\ndef sparse_matrix(matrix_array):\r\n # matrix_array_c = circulant(matrix_array)\r\n matrix_c_list = matrix_array.tolist()\r\n\r\n matrix_sparse = np.zeros(shape=matrix_array.shape)\r\n n1 = 1\r\n for r in matrix_c_list:\r\n n2 = 1\r\n for i in r:\r\n if n2 > n1:\r\n matrix_sparse[n1 - 1, n2 - 1] = 0\r\n else:\r\n matrix_sparse[n1 - 1, n2 - 1] = i\r\n n2 += 1\r\n n1 += 1\r\n matrix_array_sparse = np.array(matrix_sparse)\r\n return matrix_array_sparse\r\n\r\n\r\ndef deconv_circulant_matrix_fourier(array_ct_value_aif, array_ct_value_tissue):\r\n \"\"\"\r\n aif * r = tissue,\r\n r = solve(aif, tissue)\r\n \"\"\"\r\n\r\n # residual_func = solve_circulant(array_ct_value_aif, array_ct_value_tissue, singular='lstsq')\r\n array_ct_value_aif = svd_denoising(array_ct_value_aif)\r\n residual_func = solve(circulant(array_ct_value_aif), array_ct_value_tissue)\r\n # residual_func = ifft(fft(array_ct_value_tissue) / fft(array_ct_value_aif))\r\n return residual_func\r\n\r\n\r\ndef svd_denoising(array_1d):\r\n \"\"\"\r\n \"\"\"\r\n matrix_cir = circulant(array_1d)\r\n matrix_cir_sparse = sparse_matrix(matrix_cir)\r\n u, sigma, vt = np.linalg.svd(matrix_cir_sparse)\r\n\r\n threshold = sigma[2] * 0.10\r\n\r\n sigma_denoised = np.zeros([len(array_1d), len(array_1d)])\r\n for i in range(len(array_1d)):\r\n if sigma[i] > threshold:\r\n sigma_denoised[i][i] = sigma[i]\r\n else:\r\n sigma_denoised[i][i] = 0\r\n\r\n matrix_cir_sparse_new = np.dot(np.dot(u, sigma_denoised), vt)\r\n array_1d_new = matrix_cir_sparse_new[:, 0]\r\n return array_1d_new\r\n\r\n\r\ndef deconv_nonparam_alg_tikhonov_svd(array_ct_value_aif, array_ct_value_tissue, lamdaa):\r\n \"\"\"Deconvolution-based / Non-parametric / Tikhonov SVD\r\n \"\"\"\r\n a = array_ct_value_aif\r\n c = array_ct_value_tissue\r\n\r\n a_pad = np.pad(a, (0, len(a)))\r\n c_pad = np.pad(c, (0, len(a)))\r\n\r\n I = np.identity(2 * len(a))\r\n\r\n A = circulant(a_pad)\r\n A_T = A.T\r\n\r\n block_cirMat = np.dot(A_T, A) + (lamdaa ** 2) * I\r\n b = solve(block_cirMat, A_T @ c_pad)\r\n\r\n b = b[0:len(a)]\r\n return b\r\n\r\n\r\ndef drive_singal(seq):\r\n power = np.zeros_like(seq)\r\n for i in range(len(power) - 1):\r\n res = seq[i + 1] - seq[i]\r\n if res > 0:\r\n power[i] = 1\r\n elif res == 0:\r\n power[i] = 0\r\n else:\r\n power[i] = -1\r\n\r\n for j in range(len(power) - 1):\r\n res = power[j]\r\n if j - 1 < 0:\r\n continue\r\n if res == 0 and power[j - 1] > 0:\r\n power[j] = 1\r\n elif res == 0 and power[j - 1] < 0:\r\n power[j] = -1\r\n return power\r\n\r\n\r\ndef find_valley_peak(seq):\r\n '''\r\n Input:\r\n signal sequence\r\n Output:\r\n power signal\r\n '''\r\n # take the derivative twice for getting movement trend\r\n fir_p = drive_singal(seq)\r\n sec_p = drive_singal(fir_p)\r\n return sec_p\r\n\r\n\r\ndef find_mostRight(seq, target=-1):\r\n max_idx = 0\r\n max_len = 0\r\n temp = 0\r\n for i in range(len(seq)):\r\n if seq[i] == target:\r\n temp += 1\r\n else:\r\n if temp > max_len:\r\n max_idx = i - 1\r\n max_len = temp\r\n temp = 0\r\n return max_idx\r\n\r\n\r\ndef find_longestLine(seq, target=-1):\r\n '''\r\n Input:\r\n Power signal\r\n Output:\r\n start and end valley around peak\r\n Descirbe:\r\n Shift windows, O(n)\r\n '''\r\n q_p = 0\r\n s_p = 0\r\n max_len = 0\r\n max_r = 0\r\n while s_p < len(seq):\r\n if seq[s_p] == target:\r\n q_p = s_p\r\n while q_p + 1 < len(seq) and seq[q_p + 1] == target:\r\n q_p += 1\r\n if (q_p - s_p) >= max_len:\r\n max_len = q_p - s_p\r\n max_r = q_p\r\n s_p = q_p + 1\r\n else:\r\n s_p += 1\r\n return max(max_r - max_len, 0), max_r\r\n\r\n\r\ndef truncate_tissue(signal_seq):\r\n '''\r\n input:\r\n signal sequence\r\n output:\r\n the left and right boundary indexes of peak\r\n '''\r\n # peak is -1, valley is 1\r\n sec_power = find_valley_peak(signal_seq) # power signal\r\n left_side = np.min(np.where(sec_power == 1))\r\n peak_p = np.argmax(signal_seq[left_side:]) + left_side\r\n\r\n _, right_side = find_longestLine(sec_power[peak_p:], target=-1) + peak_p\r\n\r\n return left_side, right_side\r\n\r\n\r\ndef truncate_aif(signal_seq):\r\n sec_power = find_valley_peak(signal_seq) # power signal\r\n left_side = np.min(np.where(sec_power == 1)) + 1 # get first 1 in power signal\r\n right_side = find_mostRight(sec_power)\r\n\r\n return left_side, right_side\r\n\r\n\r\ndef baseline_correction(signal_seq, name=\"tissue\"):\r\n '''\r\n input :\r\n signal sequence\r\n output :\r\n res : peak of signal\r\n base_signal: signal sequence without baseline shift\r\n\r\n '''\r\n base_signal = BaselineRemoval(signal_seq).IModPoly(2) # getting off baseline shift\r\n\r\n if name == \"tissue\":\r\n left_side, right_side = truncate_tissue(base_signal) # get the left and right boundary of peak indexes\r\n else:\r\n left_side, right_side = truncate_aif(base_signal)\r\n\r\n res = copy.deepcopy(base_signal)\r\n\r\n # --- pick peak ---\r\n res[:left_side] = 0\r\n res[right_side + 1:] = 0\r\n res[res < 0] = 0\r\n return res, base_signal\r\n\r\n\r\ndef filter_lp(data, cutoff_l, cutoff_h, ftype):\r\n \"\"\"\r\n low pass filter\r\n \"\"\"\r\n if ftype == \"lowpass\":\r\n b, a = signal.butter(9, cutoff_h, 'lowpass')\r\n elif ftype == \"bandpass\":\r\n b, a = signal.butter(7, [cutoff_l, cutoff_h], 'bandpass')\r\n filtedData = signal.filtfilt(b, a, data)\r\n return filtedData\r\n\r\n\r\ndef deconvolution(array_ct_value_aif, array_ct_value_tissue, show=False):\r\n cir_aif = circulant(array_ct_value_aif)\r\n inv_sig = regulSig(cir_aif)\r\n # print('Condition Num:',np.linalg.cond(inv_sig))\r\n irf = inv_sig @ array_ct_value_tissue\r\n if show:\r\n return irf, inv_sig[0]\r\n else:\r\n return irf\r\n\r\n\r\ndef regulSig(cir_mat):\r\n size = cir_mat.shape[0]\r\n peakposi = np.argmax(cir_mat[:, 0])\r\n cir_mat = np.linalg.inv(cir_mat)\r\n\r\n for ii in range(size):\r\n head = cir_mat[ii][:ii]\r\n tail = cir_mat[ii][ii:]\r\n cir_mat[ii, :] = np.r_[tail, head]\r\n ans = cir_mat.mean(0)\r\n\r\n peaks, properties = find_peaks(ans, prominence=0, width=[0, 2])\r\n left_bases = properties['left_bases']\r\n right_bases = properties['right_bases']\r\n idex = np.argmax(ans[peaks])\r\n\r\n left = left_bases[idex] if abs(left_bases[idex] - peakposi) < abs(right_bases[idex - 1] - peakposi) else \\\r\n right_bases[idex - 1]\r\n right = right_bases[idex] if abs(right_bases[idex] - peakposi) < abs(left_bases[idex + 1] - peakposi) else \\\r\n left_bases[idex + 1]\r\n\r\n leftpart = ans[:left]\r\n rightpart = ans[right:]\r\n midpart = ans[left: right]\r\n\r\n leftpart = cv2.GaussianBlur(leftpart, (1, 3), 0.7)\r\n rightpart = cv2.GaussianBlur(rightpart, (1, 3), 0.7)\r\n ans = np.r_[leftpart.squeeze(-1), midpart, rightpart.squeeze(-1)]\r\n return circulant(ans).T\r\n\r\n\r\ndef show_signal(mat, tissue):\r\n size = len(mat)\r\n plt.figure(figsize=(15, 7))\r\n col_num = 8\r\n row_num = np.ceil(size / col_num)\r\n for i in range(size):\r\n plt.subplot(row_num, col_num, i + 1)\r\n plt.plot(mat[i, :])\r\n plt.plot(tissue)\r\n plt.show()\r\n\r\n\r\ndef get_center(mask):\r\n index = np.where(mask != 0)\r\n center_y = int(index[0].mean())\r\n center_x = int(index[1].mean())\r\n return center_y, center_x\r\n\r\n\r\ndef extract_cbf(cbf_img, seed, brain_mask):\r\n '''\r\n Input:\r\n 1.the cbf image getting from Ais-system\r\n 2.seed is the location of maximal lesion value in irf image\r\n 3.brain_mask is the main matter of brain\r\n Output:\r\n lesion core extracted from cbf image\r\n\r\n Describe:\r\n 1. Enhence the contrast ratio of Input Image using Clahe.\r\n 2. Calculate the power image at x and y directions, and conbine together.\r\n 3. Enhencing the contrast ratio by expanding distribution between [0, 1] using log correction function, a * log(1 + x).\r\n 4. Split the power image into two parts, basin and ridge, using otsu or cluster.\r\n 5. Locating the target basin area through seed location, the ridge around target basin is contour of lesion in cbf image.\r\n 6. Mapping pixel location into distance from seed location.\r\n 7. Spliting brain into three parts, drop off the part farthest away from target area and select the part closest to seed location.\r\n\r\n '''\r\n h, w = cbf_img.shape\r\n x, y = seed\r\n aeh_img = exposure.equalize_adapthist(cbf_img / 255, kernel_size=None, clip_limit=0.01, nbins=256)\r\n sobel_x = cv2.Sobel(aeh_img, cv2.CV_64F, 1, 0, ksize=3)\r\n sobel_y = cv2.Sobel(aeh_img, cv2.CV_64F, 0, 1, ksize=3)\r\n sobel_xy = np.sqrt(sobel_x ** 2 + sobel_y ** 2)\r\n\r\n log_img = exposure.adjust_log(sobel_xy)\r\n otsu = filters.threshold_otsu(log_img[brain_mask != 0])\r\n log_img[log_img < otsu] = 0\r\n\r\n def distance(x1, y1, x2, y2):\r\n return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\r\n\r\n dist_map = np.zeros((h, w))\r\n for row in range(h):\r\n for col in range(w):\r\n if log_img[row, col] == 0:\r\n continue\r\n dist_map[row, col] = distance(x, y, col, row)\r\n\r\n maxV = dist_map.max()\r\n minV = dist_map.min()\r\n dist_map[dist_map != 0] = maxV - dist_map[dist_map != 0] # pixel inversion\r\n\r\n dist_map = ((dist_map - minV) / (maxV - minV)) * 255\r\n res = dist_map.copy()\r\n\r\n maxV = dist_map.max()\r\n minV = dist_map[dist_map != 0].min()\r\n\r\n middle = maxV - 1 * (maxV - minV) // 3\r\n print(maxV, minV, middle)\r\n\r\n otsu = filters.threshold_otsu(dist_map[dist_map > middle])\r\n dist_map[dist_map < otsu] = 0\r\n\r\n # kernel = np.ones((2,2), 'uint8')\r\n # lesion_dilation = cv2.dilate(dist_map, kernel, iterations = 1)\r\n # lesion_erode = cv2.erode(lesion_dilation, kernel, iterations = 1)\r\n # lesion_dilation = cv2.dilate(lesion_erode, kernel, iterations = 1)\r\n\r\n ret, mask = cv2.threshold(dist_map, 127, 255, 0)\r\n # mask = cv2.drawContours(mask, sys.mask_contours, 0, (255, 0, 0), 1)\r\n # cv2.rectangle(mask, (max(0, x - 2), max(y - 2, 0)),\r\n # (min(256, x + 2),min(256, y + 2)), (227,23,13), 1)\r\n\r\n plt.figure(figsize=(15, 7))\r\n plt.subplot(1, 5, 1)\r\n plt.imshow(cbf_img)\r\n plt.title('Input Image')\r\n plt.subplot(1, 5, 2)\r\n plt.imshow(sobel_xy)\r\n plt.title('Sobel Power Image')\r\n plt.subplot(1, 5, 3)\r\n plt.imshow(log_img)\r\n plt.title('Enhance Image with Log')\r\n plt.subplot(1, 5, 4)\r\n plt.imshow(res)\r\n plt.title('Distance Image')\r\n plt.subplot(1, 5, 5)\r\n plt.imshow(mask)\r\n plt.title('Output Image')\r\n plt.show()\r\n\r\n return dist_map\r\n\r\n","sub_path":"Project/AIS System/Computation.py","file_name":"Computation.py","file_ext":"py","file_size_in_byte":11286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"86612795","text":"import torch\r\nfrom torch import nn\r\n\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n\r\nclass TransformerTTSLoss(nn.Module):\r\n \"\"\" TransformerTTS Loss \"\"\"\r\n\r\n def __init__(self):\r\n super(TransformerTTSLoss, self).__init__()\r\n\r\n def forward(self, mel_output, mel_output_postnet, gate_predicted, mel_target, gate_target):\r\n\r\n mel_target.requires_grad = False\r\n mel_loss = torch.abs(mel_output - mel_target)\r\n mel_loss = torch.mean(mel_loss)\r\n\r\n mel_postnet_loss = torch.abs(mel_output_postnet - mel_target)\r\n mel_postnet_loss = torch.mean(mel_postnet_loss)\r\n\r\n gate_loss = nn.BCEWithLogitsLoss()(gate_predicted, gate_target)\r\n\r\n return mel_loss, mel_postnet_loss, gate_loss\r\n","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"135488387","text":"import feedparser\nimport requests\nfrom actstream import action\nfrom dateutil.parser import *\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\nfrom django_bleach.models import BleachField\nfrom taggit.managers import TaggableManager\n\n\nclass Channel(models.Model):\n channel_title = models.CharField(max_length=100)\n channel_description = BleachField(allowed_tags=['', ], strip_tags=True)\n channel_image = models.URLField(blank=True)\n channel_border_color = models.TextField(default='grey')\n channel_slug = models.SlugField(unique=True)\n channel_rss_feed = models.URLField(null=True, blank=True)\n channel_tags = TaggableManager(blank=True)\n\n def __str__(self):\n return self.channel_title\n\n def get_absolute_url(self):\n return reverse(\"ChannelView\", kwargs={\"channel_slug\": self.channel_slug})\n\n\nclass Item(models.Model):\n channel = models.ForeignKey(Channel, on_delete=models.CASCADE)\n item_title = models.CharField(max_length=100)\n item_description = BleachField(allowed_tags=['p', 'b', 'i', 'em', 'strong', 'a'],\n allowed_attributes=['href', 'title', 'style', ], strip_tags=True)\n item_published = models.DateTimeField(null=True, blank=True)\n item_slug = models.SlugField(null=True, blank=True)\n item_image = models.URLField(blank=True)\n item_tags = TaggableManager(blank=True)\n\n @property\n def activity_actor_attr(self):\n return self.channel\n\n def __str__(self):\n return self.item_title\n\n def get_absolute_url(self):\n return reverse(\"ItemView\", kwargs={\"channel_slug\": self.channel.channel_slug, \"item_slug\": self.item_slug})\n\n def save(self, *args, **kwargs):\n super().save(*args, **kwargs)\n action.send(self.channel, verb='released', action_object=self, timestamp=self.item_published)\n\n\nclass FeedURL(models.Model):\n url = models.URLField()\n\n def save(self, *args, **kwargs):\n try:\n url = requests.get(self.url)\n feed = feedparser.parse(url.content)\n feed_channel_title = feed.feed.title\n\n if Channel.objects.filter(channel_title=feed_channel_title).exists():\n channel_title = Channel.objects.get(channel_title=feed_channel_title)\n for item in feed.entries:\n item_title = item.title\n if Item.objects.filter(item_title=item_title).exists():\n pass\n else:\n max_length = Item._meta.get_field('item_slug').max_length\n item_slug = slugify(item.title)[:max_length]\n item_description = item.description\n datestring = item.published\n item_published = parse(datestring)\n Item.objects.create(channel=channel_title, item_title=item_title,\n item_description=item_description, item_published=item_published,\n item_slug=item_slug)\n else:\n feed_channel_description = feed.feed.description\n feed_channel_image_url = feed.feed.image.href\n feed_channel_title_slug = slugify(feed.feed.title)\n Channel.objects.create(channel_title=feed_channel_title, channel_description=feed_channel_description,\n channel_image=feed_channel_image_url, channel_slug=feed_channel_title_slug)\n\n for item in feed.entries:\n item_title = item.title\n max_length = Item._meta.get_field('item_slug').max_length\n item_slug = slugify(item.title)[:max_length]\n item_description = item.description\n datestring = item.published\n item_published = parse(datestring)\n channel_title = Channel.objects.get(channel_title=feed_channel_title)\n Item.objects.create(channel=channel_title, item_title=item_title,\n item_description=item_description, item_published=item_published,\n item_slug=item_slug)\n\n super().save(*args, **kwargs)\n except:\n pass\n\n def __str__(self):\n return self.url\n\n\nimport threading\n\n\ndef getter():\n try:\n urls = FeedURL.objects.all()\n for rss in urls:\n url = requests.get(rss.url)\n feed = feedparser.parse(url.content)\n feed_channel_title = feed.feed.title\n channel_title = Channel.objects.get(channel_title=feed_channel_title)\n for item in feed.entries:\n item_title = item.title\n if Item.objects.filter(item_title=item_title).exists():\n pass\n else:\n max_length = Item._meta.get_field('item_slug').max_length\n item_slug = slugify(item.title)[:max_length]\n item_description = item.description\n datestring = item.published\n item_published = parse(datestring)\n Item.objects.create(channel=channel_title, item_title=item_title,\n item_description=item_description, item_published=item_published,\n item_slug=item_slug)\n except:\n pass\n threading.Timer((60 * 10), getter).start()\n\n # automatically get new episodes\n # getter()\n","sub_path":"feed/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"573703628","text":"#!/usr/bin/env python2\nfrom gimpfu import *\nimport os\nimport urllib2\nimport ssl\n\nlabel_colors = {\n 'Road': (0x40, 0x20, 0x20),\n 'Lanemarkings': (0xff, 0x00, 0x00),\n 'Undrivable': (0x80, 0x80, 0x60),\n 'Movable': (0x00, 0xff, 0x66),\n 'Mycar': (0xcc, 0x00, 0xff),\n}\n\n\ndef _find_mask_layer(image):\n mask_layer = None\n for layer in image.layers:\n if layer.name == 'mask':\n return layer\n\n\ndef _mask_file_name(image):\n fn = pdb.gimp_image_get_filename(image)\n return os.path.join(os.path.dirname(os.path.dirname(fn)), 'masks', os.path.basename(fn))\n\n\nrepo_url_base = 'https://github.com/commaai/comma10k/raw/master/masks/'\n\ndef _mask_file_url(image):\n fn = pdb.gimp_image_get_filename(image)\n return repo_url_base + os.path.basename(fn)\n\n\ndef _dowload_file(url, local_path, progress_text):\n pdb.gimp_progress_init(progress_text, None)\n try:\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n u = urllib2.urlopen(url, context=ctx)\n with open(local_path, 'wb') as f:\n meta = u.info()\n file_size = int(meta.getheaders(\"Content-Length\")[0])\n file_size_dl = 0\n block_sz = 4192\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n file_size_dl += len(buffer)\n f.write(buffer)\n pdb.gimp_progress_update(file_size_dl * 100. / file_size)\n finally:\n pdb.gimp_progress_end()\n\n\t\ndef load_mask_file(image, drawable):\n mask_layer = _find_mask_layer(image)\n if mask_layer != None:\n gimp.message(\"Mask file already loaded\")\n return\n\n mask_layer = pdb.gimp_file_load_layer(image, _mask_file_name(image))\n mask_layer.opacity = 60.0\n mask_layer.name = 'mask'\n pdb.gimp_image_insert_layer(image, mask_layer, None, -1)\n\n\ndef save_mask_file(image, drawable):\n mask_layer = _find_mask_layer(image)\n if not mask_layer:\n gimp.message(\"Mask file not loaded yet\")\n return\n pdb.gimp_selection_none(image)\n mask_fn = _mask_file_name(image)\n pdb.file_png_save2(image, mask_layer, mask_fn, mask_fn, 0, 9, 0, 0, 0, 0, 0, 0, 0)\n pdb.gimp_image_remove_layer(mask_layer)\n load_mask_file(image, drawable)\n\n\ndef load_github_mask_file(image, drawable):\n layer_name = 'github mask'\n for layer in image.layers:\n if layer.name == layer_name:\n pdb.gimp_image_remove_layer(image, layer)\n break\n url = _mask_file_url(image)\n progress_text = 'Downloading mask for {}'.format(url.split('/')[-1])\n tmp_png_fn = pdb.gimp_temp_name('png')\n _dowload_file(url, tmp_png_fn, progress_text)\n if not os.path.exists(tmp_png_fn):\n pdb.gimp_message('Downloading from github failed.')\n return\n github_mask_layer = pdb.gimp_file_load_layer(image, tmp_png_fn)\n github_mask_layer.opacity = 90.0\n github_mask_layer.name = layer_name\n pdb.gimp_image_insert_layer(image, github_mask_layer, None, -1)\n github_mask_layer.visible = True\n mask_layer = _find_mask_layer(image)\n if mask_layer != None:\n mask_layer.opacity = 90.0\n return\n\n\ndef label_selected_pixels(image, drawable, category_name):\n mask_layer = _find_mask_layer(image)\n if not mask_layer:\n gimp.message(\"Mask file not loaded yet\")\n return\n if pdb.gimp_selection_is_empty(image):\n pdb.gimp_message(\"You must first select a region.\")\n return\n pdb.gimp_context_set_foreground(label_colors[category_name])\n pdb.gimp_edit_fill(mask_layer, 0)\n #pdb.gimp_selection_none(image)\n mask_layer.visible = True\n\n\nregister(\n \"comma10k_load_mask_file\",\n \"Load Mask File\",\n \"Load Mask File\",\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"/Comma10K/Load Mask File\",\n \"RGB*, GRAY*\",\n [],\n [],\n load_mask_file\n)\n\nregister(\n \"comma10k_save_mask_file\",\n \"Save Mask File\",\n \"Save Mask File\",\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"/Comma10K/Save Mask File\",\n \"RGB*, GRAY*\",\n [],\n [],\n save_mask_file\n)\n\nregister(\n \"comma10k_load_github_mask_file\",\n \"Load Github Mask File\",\n \"Load Github Mask File\",\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"/Comma10K/Load Old Mask from github\",\n \"RGB*, GRAY*\",\n [],\n [],\n load_github_mask_file\n)\n\n\nfor category_name in label_colors.keys():\n register(\n \"comma10k_set_foreground_color_%s\" % category_name,\n \"Set FColor to %s\" % category_name,\n \"Set FColor to %s\" % category_name,\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"/Comma10K/Set Foreground Color to/%s\" % category_name,\n \"RGB*, GRAY*\",\n [],\n [],\n lambda img, l, category_name=category_name: pdb.gimp_context_set_foreground(label_colors[category_name])\n )\n\n register(\n \"comma10k_label_selected_pixels_as_%s\" % category_name,\n \"Label selected pixels as %s\" % category_name,\n \"Label selected pixels as %s\" % category_name,\n \"https://github.com/nanamiwang\",\n \"https://github.com/nanamiwang\",\n \"2020\",\n \"/Comma10K/Label Selected Pixels as/%s\" % category_name,\n \"RGB*, GRAY*\",\n [],\n [],\n lambda img, l, category_name=category_name: label_selected_pixels(img, l, category_name)\n )\n\nmain()\n","sub_path":"gimp_plugin/gimp_comma10k_helpers.py","file_name":"gimp_comma10k_helpers.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"520251358","text":"infile = open(\"fibo.hex\", \"r\")\noutfile = open(\"fibo\", \"w\")\n\nscale = 16 ## equals to hexadecimal\n\nnum_of_bits = 8\n\nfor line in infile:\n hex_string = line.strip()\n outfile.write(bin(int(hex_string, scale))[2:].zfill(num_of_bits))\n outfile.write(\"\\n\")\n\nprint(\"Worked\")\n\ninfile.close()\noutfile.close()\n","sub_path":"hextobin.py","file_name":"hextobin.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"51110434","text":"#BOJ 2133 타일 채우기\n\nN = int(input())\n\ndpList = [0 for i in range(0,31)]\ndpList[0] = 1\ndpList[2] = 3\ndpList[4] = 11\n\nfor i in range(6, N+1,2):\n dpList[i] = dpList[i-2]*3\n for j in range(4, i+1, 2):\n dpList[i] += 2*dpList[i-j]\n\nif N % 2 == 1:\n print(0)\nelse:\n print(dpList[N])\n","sub_path":"Dynamic Programming/BOJ_2133_타일채우기.py","file_name":"BOJ_2133_타일채우기.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"597353863","text":"\ndef main():\n required = -1\n while required <= 0:\n required = int(input(\"Enter the number of items being shipped\"))\n itemCosts = [\"\"] * required\n totalCost = 0\n for i in range(0,required,1):\n print(\"Please enter cost of item:\", str(i+1))\n itemCosts[i] = int(input())\n totalCost += itemCosts[i]\n\n print(\"Number of items:\", required)\n for i in range(0,required,1):\n print(\"Price of item:\", itemCosts[i])\n\n if totalCost > 100:\n totalCost = totalCost * 0.9\n print(\"Total cost for shipping\", required, \"items is:\", totalCost)\n\nmain()\n\n\n\n\n\n","sub_path":"Prac_01/shippingCalculator.py","file_name":"shippingCalculator.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"362259065","text":"\"\"\"Local settings for use within Django app. Requires reload / rebuild to pick up for deploy.\"\"\"\nimport os\nfrom django.conf import settings\n\n# Default Settings Overrides\nSECRET_KEY = os.getenv('APP_SECRET_KEY', 'blergh')\nDEBUG = bool(os.getenv('APP_DEBUG_MODE', False))\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1',\n os.getenv('APP_HOST'),\n os.getenv('APP_FQDN')\n]\n\n# Deployment type\nCOMBINE_DEPLOYMENT = os.getenv('COMBINE_DEPLOYMENT', 'server')\n\n# Combine Install Location\nCOMBINE_INSTALL_PATH = os.getenv('COMBINE_INSTALL_PATH', '/opt/combine')\n\n# Combine Front-End\nAPP_HOST = os.getenv('APP_HOST', '127.0.0.1')\n\n# Spark Cluster Information\nSPARK_HOST = os.getenv('SPARK_HOST', '127.0.0.1')\nSPARK_PORT = int(os.getenv('SPARK_PORT', 8080))\n# if taken, will automatically increment +100 from here until open port is found\nSPARK_APPLICATION_ROOT_PORT = 4040\n\n# Spark tuning\nSPARK_MAX_WORKERS = int(os.getenv('SPARK_MAX_WORKERS', 1))\nJDBC_NUMPARTITIONS = int(os.getenv('JDBC_NUMPARTITIONS', 200))\nSPARK_REPARTITION = int(os.getenv('SPARK_REPARTITION', 200))\nTARGET_RECORDS_PER_PARTITION = int(os.getenv('TARGET_RECORDS_PER_PARTITION', 5000))\nMONGO_READ_PARTITION_SIZE_MB = int(os.getenv('MONGO_READ_PARTITION_SIZE_MB', 4))\n\n# Apache Livy settings\n'''\nCombine uses Livy to issue spark statements.\nLivy provides a stateless pattern for interacting with Spark, and by proxy, DPLA code.\n'''\nLIVY_HOST = os.getenv('LIVY_HOST', '127.0.0.1')\nLIVY_PORT = int(os.getenv('LIVY_PORT', 8998))\nLIVY_DEFAULT_SESSION_CONFIG = {\n 'kind':'pyspark',\n 'jars':[\n 'file:///combinelib/mysql.jar'\n ],\n 'files':[\n 'file://%s/core/spark/es.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/jobs.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/record_validation.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/utils.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/spark/console.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n 'file://%s/core/xml2kvp.py' % COMBINE_INSTALL_PATH.rstrip('/'),\n ],\n\n # Spark conf overrides\n 'conf':{\n 'spark.ui.port': SPARK_APPLICATION_ROOT_PORT\n },\n}\n\n# Storage for avro files and other binary files\n'''\nMake sure to note file:// or hdfs:// prefix\n'''\nBINARY_STORAGE = os.getenv('BINARY_STORAGE', 'file:///home/combine/data/combine')\nWRITE_AVRO = bool(os.getenv('WRITE_AVRO', False))\n\n# ElasicSearch server\nES_HOST = os.getenv('ES_HOST', '127.0.0.1')\nINDEX_TO_ES = bool(os.getenv('INDEX_TO_ES', True))\n\n# ElasticSearch analysis\nCARDINALITY_PRECISION_THRESHOLD = int(os.getenv('CARDINALITY_PRECISION_THRESHOLD', 100))\nONE_PER_DOC_OFFSET = float(os.getenv('ONE_PER_DOC_OFFSET', 0.05))\n\n# Service Hub\nSERVICE_HUB_PREFIX = os.getenv('SERVICE_HUB_PREFIX', 'funcake--')\n\n# OAI Server\nOAI_RESPONSE_SIZE = int(os.getenv('OAI_RESPONSE_SIZE', 500))\nCOMBINE_OAI_IDENTIFIER = os.getenv('COMBINE_OAI_IDENTIFIER', 'oai:funnel_cake')\nMETADATA_PREFIXES = {\n 'mods':{\n 'schema':'http://www.loc.gov/standards/mods/v3/mods.xsd',\n 'namespace':'http://www.loc.gov/mods/v3'\n },\n 'oai_dc':{\n 'schema':'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',\n 'namespace':'http://purl.org/dc/elements/1.1/'\n },\n 'dc':{\n 'schema':'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',\n 'namespace':'http://purl.org/dc/elements/1.1/'\n },\n}\n\n# Database configurations for use in Spark context\nCOMBINE_DATABASE = {\n 'jdbc_url':os.getenv('MYSQL_JDBC', 'jdbc:mysql://%s:3306/combine' % settings.DATABASES['default']['HOST']),\n 'user':os.getenv('MYSQL_USER', settings.DATABASES['default']['USER']),\n 'password':os.getenv('MYSQL_PASSWORD', settings.DATABASES['default']['PASSWORD'])\n}\n\n# DPLA API\nDPLA_RECORD_MATCH_QUERY = bool(os.getenv('DPLA_RECORD_MATCH_QUERY', True))\nDPLA_API_KEY = os.getenv('DPLA_API_KEY', None)\n\n# AWS S3 Credentials\nAWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', None)\nAWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY', None)\nDPLA_S3_BUCKET = os.getenv('DPLA_S3_BUCKET', 'dpla-provider-export')\n\n# Analysis Jobs Org and Record Group\n'''\nThis dictionary provides the name of the Organization and Record Group that\nAnalysis Jobs will be created under. Because Analysis jobs are extremely similar\nto other workflow jobs, but do not lend themselves towards the established\nOrganization --> Record Group --> Job hierarchy, this ensures they are treated\nsimilarily to other jobs, but skip the need for users to manually create these\nsomewhat unique Organization and Record Group.\n - it is recommended to make these names quite unique,\n to avoid clashing with user created Orgs and Record Groups\n - the Organization and Record Group names defined in ANALYSIS_JOBS_HIERARCHY\n will NOT show up in any Org or Record Group views or other workflows\n\t- it is quite normal, and perhaps encouraged, to leave these as the defaults\n'''\nANALYSIS_JOBS_HIERARCHY = {\n # suffix is md5 hash of 'AnalysisOrganization'\n 'organization':'AnalysisOrganizationf8ed4bfcefc4dbf87b588a5de9b7cc95',\n # suffix is md5 hash of 'AnalysisRecordGroup'\n 'record_group':'AnalysisRecordGroupf660bb4826bea8b63fd773d27d687cfd'\n}\n\n# Celery Configurations\nCELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL', 'redis://localhost:6379/0')\nCELERY_RESULT_BACKEND = os.getenv('CELERY_RESULT_BACKEND', 'redis://localhost:6379/0')\n\n# StateIO Configurations\n'''\nConfigurations used for exporting/importing \"states\" in Combine, including\nOrganizations, Record Groups, Jobs, Validation Scenarios, Transformation\nScenarios, etc. These can be large in size, and potentially helpful to\npreserve, so /tmp is not ideal here.\n'''\nSTATEIO_EXPORT_DIR = os.getenv('STATEIO_EXPORT_DIR', '/home/combine/data/combine/stateio/exports')\nSTATEIO_IMPORT_DIR = os.getenv('STATEIO_IMPORT_DIR', '/home/combine/data/combine/stateio/imports')\n\n# Mongo server\nMONGO_HOST = os.getenv('MONGO_HOST', '127.0.0.1')\n\n# overrides for DATABASE settings\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': os.getenv('MYSQL_NAME', 'combine'),\n 'USER': os.getenv('MYSQL_USER', 'combine'),\n 'PASSWORD': os.getenv('MYSQL_PASSWORD', 'combine'),\n 'HOST': os.getenv('MYSQL_HOST', '127.0.0.1'),\n 'PORT': int(os.getenv('MYSQL_PORT', 3306)),\n }\n}\n","sub_path":"combine/localsettings.py","file_name":"localsettings.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"643987027","text":"#!/usr/bin/python\n\nimport sqlite3\n\nimport sys\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/yaml/lib']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/webob']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/fancy_urllib']\nsys.path += ['/Users/lambert/Projects/googleappengine-read-only/python/lib/django']\nsys.path += ['.']\n\nfrom google.appengine.datastore import entity_pb\nfrom google.appengine.api import datastore\n\nconn = sqlite3.connect('local_data/FacebookCachedObject.db', isolation_level=None)\ncursor = conn.cursor()\ncursor.execute('select id, value from result')\nfor entity_id, entity in cursor:\n entity_proto = entity_pb.EntityProto(contents=entity)\n e = datastore.Entity._FromPb(entity_proto)\n if str(entity_id).endswith('OBJ_EVENT'):\n real_id = str(entity_id).split(':')[-1]\n if 'json_data' in e:\n f = open('test_data/FacebookCachedObject/%s' % real_id, 'w')\n f.write(e['json_data'])\n f.close()\n","sub_path":"server/tools/dump_fbo_db.py","file_name":"dump_fbo_db.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"464006214","text":"#! /usr/bin/ env python\n# -*- coding:utf-8 -*-\n\n\n\"\"\"\nipset 增删改\n\nmodify log:\n 2016-6-23:\n 1、新增ipv6的ipset\n\"\"\"\n\n\nimport os\nimport json\nfrom logging import getLogger\n\nfrom db.mysqlconnect import execute_sql\nfrom utils.mask_transition import exchange_mask\nfrom objectdefine.ip_range import get_ip\nfrom utils.logger_init import logger_init\n\n\nfrom IPy import IP\n\n\n\nLOGGER_PATH = '/usr/local/bluedon/log/ipset.log'\nLOGGER_NAME = 'IPSET'\n\nlogger_init(LOGGER_NAME, LOGGER_PATH, 'DEBUG')\n\n\ndef set_ipset(data, action='add', iptype='ipv4'):\n \"\"\" 设置ipset \"\"\"\n\n ipset_path = '/usr/local/sbin/ipset'\n cmd_ipset = {'delipset': '%s destroy %s',\n 'ipv4': '%s creat %s hash:net',\n 'ipv6': '%s creat %s hash:net family inet6',\n 'change_ipset': '%s %s %s %s'}\n\n # 创建ipset\n if action == 'del':\n ipset_cmd = cmd_ipset['delipset'] %(ipset_path, data['HideID'])\n elif action == 'add':\n ipset_cmd = cmd_ipset[iptype] %(ipset_path, data['HideID'])\n\n os.system(ipset_cmd)\n getLogger(LOGGER_NAME).debug(ipset_cmd)\n\n if action == 'del':\n return\n\n # 把ip添加到ipset中\n sip = str(data['sIP']).split(',')\n if len(sip) == 1:\n addr_sql = 'select * from m_tbaddress_list_scm where id=%s' %(sip[0])\n else:\n sip = tuple([int(item) for item in sip])\n addr_sql = 'select * from m_tbaddress_list_scm where id in %s' %(str(sip))\n results = execute_sql(addr_sql)\n for result in results:\n addr_list = ip_iprange(result)\n for addr in addr_list:\n cmd = cmd_ipset['change_ipset'] %(ipset_path, action,\n data['HideID'], addr)\n getLogger(LOGGER_NAME).debug(cmd)\n os.system(cmd)\n os.system(\"ipset save > /etc/ipset.conf\")\n #print data['HideID']\n\ndef ip_iprange(data):\n \"\"\"\n args:\n data: 记录集\n return:\n addr_list: ip列表\n \"\"\"\n\n addr_list = list()\n if data['sIPV'].lower() == 'ipv4':\n if str(data['sAddtype']).strip() == '1': # ip和掩码形式\n if data['sAddress'].endswith('.0'):\n if '.' not in data['sNetmask']:\n addr_list = ['%s/%s' %(data['sAddress'], data['sNetmask'])]\n else:\n addr_list = [IP('%s/%s' %(data['sAddress'], data['sNetmask']),\n make_net=True).strNormal(1)]\n else:\n addr_list = [data['sAddress']]\n elif str(data['sAddtype']).strip() == '2': # ip段\n iprange = '%s-%s' %(data['sAddress'], data['sNetmask'])\n addr_list = get_ip(iprange)\n else:\n addr_list = [data['sAddress']]\n return addr_list\n\ndef main(args):\n ipset_sql = 'select * from m_tbaddressgroup_scm'\n datas = execute_sql(ipset_sql)\n if not args in ['init', 'reboot']:\n return\n\n for data in datas:\n set_ipset(data, 'del', data['sGroupIPV'])\n\n if args == 'reboot':\n for data in datas:\n set_ipset(data, 'add', data['sGroupIPV'])\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) < 2:\n getLogger(LOGGER_NAME).debug('have more args! (eg: python -m objectdefine.set_ipgroup init/reboot)')\n else:\n main(sys.argv[1])\n","sub_path":"chuhuo_2.71/bluedon/scm/set_ipgroup.py","file_name":"set_ipgroup.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"643897601","text":"from django import forms\nfrom messaging.models import Message\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field\nfrom crispy_forms.bootstrap import FormActions\n\nclass NewMessageForm(forms.ModelForm):\n helper = FormHelper()\n helper.form_tag = True\n helper.form_method = 'POST'\n helper.form_class = 'form-horizontal'\n helper.label_class = 'col-sm-4'\n helper.field_class = 'col-sm-8'\n helper.layout = Layout(\n Field('to_user',css_class='input-sm' ), \n Field('short_message',css_class='input-sm'),\n FormActions(Submit('Submit', 'Submit', css_class='btn-primary'))\n )\n class Meta:\n model = Message\n fields = ('short_message',\n 'to_user')","sub_path":"tinytotts/messaging/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"286250117","text":"import inspect\nimport os\nimport re\nimport time\nfrom bs4 import BeautifulSoup as bs\nimport easygui\nimport pandas as pd\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\ndef get_chromedriver_path():\n # Get CWD and pass chromedriver to PATH env variable\n current_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))\n path_to_chromedriver = os.path.join(current_folder, 'chromedriver.exe')\n return path_to_chromedriver\n\n\nCHROME_PATH = get_chromedriver_path()\n\n\nclass FileLoader(object):\n\n def __init__(self, path):\n self.path = path\n self.output_dir = self.generate_output_dir()\n self.file = self.read_file()\n self.url_paths = self.parse_file()\n\n\n @property\n def url_search(self):\n return re.compile(r\"(http(s)?:\\/\\/.)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)\")\n\n def is_url(self, x):\n if not isinstance(x, str):\n return False\n if self.url_search.search(x):\n return True\n else:\n return False\n\n def generate_filepath(self, url):\n f = url.split(\"/\")[-1]\n f += \".html\"\n return os.path.join(self.output_dir, f)\n\n def read_file(self):\n file_ext = os.path.splitext(self.path)[1]\n if file_ext == '.csv':\n open_method = pd.read_csv\n elif file_ext == '.xls' or file_ext == '.xlsx':\n open_method = pd.read_excel\n else:\n open_method = None\n print(file_ext + \"Not supported\")\n return pd.DataFrame() # Returning an empty dataframe vs False required for truth value error from pandas\n df = open_method(self.path, header=None)\n df_ = df[[df.columns[0]]] # Drop all but first column\n del df\n col_name = df_.columns[0]\n df_.rename(columns={col_name: 'url'}, inplace=True)\n # Drop invalid URLs\n df_ = df_.loc[df_['url'].apply(lambda x: self.is_url(x))]\n df_['filepath'] = df_['url'].apply(lambda x: self.generate_filepath(x))\n return df_\n\n def parse_file(self):\n if self.file.empty:\n return []\n return dict(self.file[['url', 'filepath']].values.tolist())\n\n def generate_output_dir(self):\n cwd = os.getcwd()\n output_dir = os.path.join(cwd, 'pages_0')\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n return output_dir\n elif not os.listdir(output_dir):\n return output_dir\n else:\n counter = 1\n for i in range(1000):\n output_dir = os.path.join(cwd, 'pages_{}'.format(i))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n return output_dir\n elif not os.listdir(output_dir):\n return output_dir\n else:\n counter += 1\n\n\nclass page_status_complete(object):\n \"\"\"\n Expectation that document.readyState == 'complete'\n \"\"\"\n\n def __init__(self):\n pass\n\n def __call__(self, driver):\n page_status = driver.execute_script(\"return document.readyState\")\n if page_status == 'complete':\n return driver.page_source\n else:\n return False\n\n\nclass Nomad(object):\n\n def __init__(self, url_paths, driver_path, wait_time=30):\n self.url_paths = url_paths\n self.driver = webdriver.Chrome(executable_path=driver_path)\n self.wait_time = wait_time\n\n def add_message(self, message):\n\n \"\"\"\n Intended for displaying a message on the blank page on Chromedriver opens\n \"\"\"\n\n self.driver.execute_script(\"\"\"\n var header = document.createElement('h1'); \n var message = document.createTextNode('{}');\n header.appendChild(message);\n document.body.appendChild(header);\n \"\"\".format(message))\n\n def get_and_wait(self, url):\n self.driver.get(url)\n wait = WebDriverWait(self.driver, self.wait_time)\n page_ = wait.until(page_status_complete())\n return page_\n\n def save_page(self, soup_page, file_path):\n with open(file_path, \"wb+\") as html_file:\n html_file.write(soup_page.encode(\"utf-8\"))\n\n def fetch_pages(self):\n errors = []\n success_counter = 0\n for url, path in self.url_paths.items():\n page_ = self.get_and_wait(url)\n if not page_:\n errors.append(url)\n print(\"Error getting {}\".format(url))\n soup = bs(page_, 'html.parser')\n self.save_page(soup, path)\n print(\"Finished {}\".format(url))\n success_counter += 1\n self.driver.quit()\n return errors, success_counter\n\n\ndef intro_prompt():\n print(\"Welcome to Nomad!\")\n print(\"\")\n time.sleep(2)\n print(\"This program navigates your browser to a list of URLs.\")\n time.sleep(2)\n print(\"After visiting each page, the page is saved to your computer\")\n time.sleep(2)\n print(\"This allows for data extraction by yourself or a more knowledgeable user\")\n print(\"\")\n\n\ndef intro_file_prompt():\n print(\"==========================================================================================================\")\n print(\"\")\n print(\"Nomad expects a .csv, .xls or .xlsx file of URL's\")\n time.sleep(1)\n print(\"These must be in Column A of your spreadsheet\")\n time.sleep(1)\n print(\"There is no need to include a header\")\n\n\ndef intro_prompt_for_file():\n print(\"==========================================================================================================\")\n print(\"\")\n time.sleep(2)\n print(\"In a moment a File Open Dialog will be opened\")\n time.sleep(1)\n print(\"If it is not visible, please try minimizing other applications\")\n time.sleep(1)\n print(\"It is likely to be hidden under other open windows\")\n time.sleep(1)\n\n\ndef intro_():\n intro_prompt()\n intro_file_prompt()\n intro_prompt_for_file()\n\n\ndef intro_login():\n print(\"After Nomad opens a new Chrome browser, please visit your destination website\")\n time.sleep(1)\n print(\"You will need to login\")\n time.sleep(1)\n print(\"Nomad will wait until you are ready\")\n time.sleep(1)\n\n\ndef intro_selenium():\n has_login = input(\"Do your websites require a login? Enter (Y/N)\")\n if has_login.lower() == \"y\":\n has_login = True\n else:\n has_login = False\n if has_login:\n intro_login()\n\ndef prompt_begin():\n user_ready = input(\"Are you ready to begin? Enter (Y/N)\")\n if user_ready.lower() == \"y\":\n return True\n else:\n return False\n\n\ndef exit_nomad(message):\n print(\"============\")\n print(message)\n counter = 5\n for i in range(5):\n print(\"Nomad exiting in {}\".format(counter))\n time.sleep(1)\n counter -= 1\n quit()\n\n\ndef error_on_file():\n exit_nomad(\"Nomad was not able to open the file you selected and will now exit\")\n\n\ndef output_results(errors, success_counts):\n if len(errors) == 0:\n print(\"Great news! Nomad was able to get all {} of your URLs\".format(success_counts))\n time.sleep(5)\n exit_nomad(\"Goodbye!\")\n elif len(errors) > 0 and success_count > 0:\n print(\"The good news is that Nomad was able to get {} of your URLs\".format(success_counts))\n print(\"The bad news is that Nomad could not get {} of them\".format(len(errors)))\n print(\"They were : \")\n for e in errors:\n print(e)\n time.sleep(30)\n exit_nomad(\"Goodbye!\")\n else:\n print(\"Well that's embarrassing, Nomad was unable to get any of your URLs\")\n exit_nomad(\"Goodbye!\")\n\n\nif __name__ == '__main__':\n intro_()\n path_in = easygui.fileopenbox(msg=\"Select the Spreadsheet containing URLS\", title=\"Nomad\")\n fileloader = FileLoader(path_in)\n if fileloader.file.empty:\n error_on_file()\n quit()\n intro_selenium()\n # Create a Nomad object\n # Passing FileLoaders\n\n nomad = Nomad(fileloader.url_paths, CHROME_PATH)\n nomad.add_message(\"Please indicate via the console when you are ready to begin\")\n user_ready = prompt_begin()\n if not user_ready:\n nomad.driver.quit()\n exit_nomad(\"Please restart Nomad when you are ready\")\n errors, success_count = nomad.fetch_pages()\n output_results(errors, success_count)\n","sub_path":"Nomad/nomad.py","file_name":"nomad.py","file_ext":"py","file_size_in_byte":8463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"129602702","text":"\n\n#calss header\nclass _IDENTIFY():\n\tdef __init__(self,): \n\t\tself.name = \"IDENTIFY\"\n\t\tself.definitions = [u'to recognize someone or something and say or prove who or what that person or thing is: ', u'to recognize a problem, need, fact, etc. and to show that it exists: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_identify.py","file_name":"_identify.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"7292389","text":"import numpy\nimport os\n\nfrom __main__ import send_cmd_help\nfrom .utils import checks\nfrom .utils.chat_formatting import pagify\nfrom .utils.dataIO import dataIO\nfrom discord.ext import commands\n\n\nclass Lootbox:\n\n def __init__(self, bot):\n self.bot = bot\n self.db = dataIO.load_json(\"data/lootbox/servers.json\")\n\n @commands.group(pass_context=True)\n async def box(self, ctx):\n \"\"\"Box related commands\"\"\"\n if ctx.invoked_subcommand is None:\n await send_cmd_help(ctx)\n\n @box.command(pass_context=True)\n async def add(self, ctx, name: str, content: str, multi: int=None):\n \"\"\"Adds items to a box\n Usage:\n winter = box name\n [p]box add winter Key 20\n [p]box add winter \"Key, Unsealing Charm\" 20\"\"\"\n name = name.lower()\n server = ctx.message.server\n counter = 0\n neg = False\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please use [p]box create first\")\n return\n if \", \" in content:\n content = content.split(\", \")\n elif \",\" in content:\n content = content.split(\",\")\n if multi and type(content) is not list:\n if multi < 0:\n neg = True\n multi = abs(multi)\n content = [content.lower()] * multi\n else:\n if multi < 0:\n neg = True\n multi = abs(multi)\n content = content * multi\n print(content)\n for x in content:\n x = x.lower()\n if x in self.db[server.id][name][\"content\"]:\n if neg:\n self.db[server.id][name][\"content\"][x] -= 1\n else:\n self.db[server.id][name][\"content\"][x] += 1\n else:\n counter += 1\n continue\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"Items added to {} box: {}. Items failed to add: \"\n \"{}\".format(name, len(content)-counter, counter))\n\n @box.command(pass_context=True)\n async def create(self, ctx, name: str, output: int, *, content: str):\n \"\"\"Creates a box in the current server\n [p]box create winter 6 Key, Unsealing Charm, Black Padded Coat, Infernal Horn\"\"\"\n name = name.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if name in self.db[server.id]:\n await self.bot.say(\"Box already exists, please use another name or use box edit to change the contents\")\n return\n if \", \" in content:\n content = content.split(\", \")\n elif \",\" in content:\n content = content.split(\",\")\n self.db[server.id][name] = {\"content\": {}, \"output\": output}\n for x in content:\n x = x.lower()\n self.db[server.id][name][\"content\"][x] = 0\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} box has been added, it has {} items and outputs {}\"\n \" items\".format(name, len(content), output))\n\n @checks.mod_or_permissions()\n @box.group(pass_context=True)\n async def edit(self, ctx):\n \"\"\"Allows editing of box names or output\"\"\"\n if ctx.invoked_subcommand is None:\n await send_cmd_help(ctx)\n\n @edit.command(pass_context=True)\n async def name(self, ctx, name: str, newname: str):\n \"\"\"Allows editing of the boxes' name\n winter = current name\n autumn = new name\n [p]box edit name winter autumn\"\"\"\n name = name.lower()\n newname = newname.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if newname in self.db[server.id]:\n await self.bot.say(\"Box already exists, please use another name\")\n return\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n self.db[server.id][newname] = self.db[server.id].pop(name, None)\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} has been renamed to {}\".format(name, newname))\n\n @edit.command(pass_context=True)\n async def output(self, ctx, name: str, output: int):\n \"\"\"Allows adjusting how many items\n come out of the simulated lootbox\n [p]box edit output 20\"\"\"\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n self.db[server.id][name][\"output\"] = output\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} box's output has changed to {}\".format(name, output))\n\n @edit.command(pass_context=True)\n async def append(self, ctx, name: str, items: str):\n \"\"\"Allows adding new items to an already created lootbox\n [p]box edit append \"item_1 1, item_2 4, item_3 5\"\n Names are fixed when they are added.\"\"\"\n server = ctx.message.server\n items = items.split(\", \")\n itemis = dict()\n for item in items:\n item, value = item.split(\" \")\n item = item.replace(\"_\", \" \").lower()\n itemis[item] = value\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n items = list(itemis.keys())\n for item in items:\n value = itemis[item]\n if item in self.db[server.id][name][\"content\"]:\n items = [item for item in items if item not in self.db[server.id][name][\"content\"]]\n else:\n self.db[server.id][name][\"content\"][item] = value\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n if items:\n await self.bot.say(\"{} box has added the following items:\\n{}\".format(name, \"\\n\".join(items)))\n else:\n await self.bot.say(\"{} box hasn't added any new items\".format(name))\n\n @edit.command(pass_context=True)\n async def remove(self, ctx, name: str, items: str):\n \"\"\"Allows removing items to an already created lootbox\n [p]box edit remove \"item_1 1, item_2 4, item_3 5\"\n Names are fixed when they are added.\"\"\"\n server = ctx.message.server\n items = items.split(\", \")\n itemis = dict()\n for item in items:\n item, value = item.split(\" \")\n item = item.replace(\"_\", \" \").lower()\n itemis[item] = value\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Box doesn't exist, please make sure the spelling is correct and\"\n \" that it's found in [p]box list\")\n return\n for item in itemis:\n value = itemis[item]\n print(item)\n if item in self.db[server.id][name][\"content\"]:\n del itemis[item]\n continue\n else:\n self.db[server.id][name][\"content\"][item] = value\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"{} box's has added the following items:\\n{}\".format(name, \"\\n\".join(list(itemis))))\n\n @box.command(pass_context=True)\n async def info(self, ctx, name: str):\n \"\"\"Shows info on the box, it's contents\n and the probability of getting an item\"\"\"\n name = name.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n if name not in self.db[server.id]:\n await self.bot.say(\"Please make sure that the name is spelled correctly and \"\n \"that you can find it in [p]box list\")\n return\n box = list(self.db[server.id][name][\"content\"].keys())\n values = list(self.db[server.id][name][\"content\"].values())\n value = sum(values)\n for x in range(len(values)):\n values[x] = values[x]/value\n box[x] = \" {:.2%} chance of getting \".format(values[x]) + box[x]\n msg = \"You can get the following items from the box:\\n\"\n msg += \"\\n\".join(box)\n for page in pagify(msg):\n await self.bot.say(page)\n\n @box.command(pass_context=True)\n async def list(self, ctx):\n \"\"\"Shows existing boxes in the current server\"\"\"\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n if len(self.db[server.id]) < 1:\n await self.bot.say(\"No boxes have been created for this server yet, please create some using [p]box create\"\n \" first, thanks\")\n return\n boxes = self.db[server.id].keys()\n await self.bot.say(\"Here are this server's boxes:\\n{}\".format(\"\\n\".join(boxes)))\n\n @checks.is_owner()\n @box.command(pass_context=True)\n async def remove(self, ctx, name: str):\n \"\"\"Deletes existing boxes\"\"\"\n name = name.lower()\n server = ctx.message.server\n if name not in self.db[server.id]:\n await self.bot.say(\"Please make sure that the name is spelled correctly and \"\n \"that you can find it in [p]box list\")\n return\n del self.db[server.id][name]\n dataIO.save_json(\"data/lootbox/servers.json\", self.db)\n await self.bot.say(\"Box has been removed\")\n\n @box.command(pass_context=True)\n async def sim(self, ctx, name: str, item: str=None):\n \"\"\"Simulates the opening of a box (It won't be as accurate as an actual lootbox)\n If an item is always in a box, put the item name spelled correctly,\n with capitalization and all\n if you have Key in a box called winter do:\n [p]box sim winter Key\"\"\"\n name = name.lower()\n item = item.lower()\n server = ctx.message.server\n if server.id not in self.db:\n self.db[server.id] = {}\n if name not in self.db[server.id]:\n await self.bot.say(\"Please make sure that the name is spelled correctly and \"\n \"that you can find it in [p]box list\")\n return\n box = list(self.db[server.id][name][\"content\"].keys())\n output = self.db[server.id][name][\"output\"]\n values = list(self.db[server.id][name][\"content\"].values())\n if item:\n try:\n y = box.index(item)\n del box[y]\n del values[y]\n output = output - 1\n except ValueError:\n item = None\n value = sum(values)\n for x in range(len(values)):\n values[x] = values[x]/value\n meow = numpy.random.choice(box, output, replace=False, p=values)\n if item:\n counter = numpy.random.randint(0, len(meow))\n meow = numpy.insert(meow, counter, item)\n msg = \"From {} box you got:\\n\".format(name)\n msg += \"\\n\".join(meow)\n for page in pagify(msg, delims=[\"\\n\"]):\n await self.bot.say(page)\n\n\ndef check_folders():\n # create data/lootbox if not there\n if not os.path.exists('data/lootbox'):\n print('Creating data/lootbox folder...')\n os.mkdir('data/lootbox')\n\n\ndef check_files():\n # create servers.json if not there\n # put in default values\n default = {}\n if not os.path.isfile('data/lootbox/servers.json'):\n print('Creating default lootbox servers.json...')\n dataIO.save_json('data/lootbox/servers.json', default)\n\n\ndef setup(bot):\n check_folders()\n check_files()\n n = Lootbox(bot)\n bot.add_cog(n)\n","sub_path":"lootbox/lootbox.py","file_name":"lootbox.py","file_ext":"py","file_size_in_byte":12523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"364122762","text":"# def ticket(price=5):\n# amount = int(input('Сколько вы хотите купить билетов? '))\n# return amount*price\n\n# print(ticket(int(input(\"Билеты\"))))\n\nimport random\nimport time\n\ndef display_intro():\n print('Ты - Шрек, спасающий Фиону.\\nСейчас ты находишься между 2 башнями.\\nВ одной башне тебя ждет Фиона.\\nА в другой - дракон, который за секунду тебя испепелит.')\n\ndef choose_tower():\n sick=int(input('Выбери башню '))\n while sick!=1 and sick!=2:\n sick=int(input('Выбери башню '))\n return sick\n\ndef check_tower(chosenTower):\n print('Вы приближаетесь к башне..')\n time.sleep(2)\n print('Она тёмная и жуткая..')\n time.sleep(2)\n print('Перед тобой резко открывается дверь и из нее на тебя пристально смотрит...')\n print('---------------------------------')\n time.sleep(2)\n jode = random.randint(1,2)\n if jode==chosenTower:\n print('Ты спас Фиону!')\n else:\n print('Тебя сжёг дракон :(')\n\nstart_game='yes'\nwhile start_game=='yes' or start_game=='y':\n display_intro()\n check_tower(choose_tower())\n start_game=input('Хочешь сыграть еще раз? ')\n\n","sub_path":"def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"358609747","text":"\"\"\"\ndf.py\n\"\"\"\nimport warnings\nimport copy\nimport numbers\nfrom ctypes import *\nfrom array import array\nimport numpy as np\nimport pandas as pd\nfrom collections import Iterable, OrderedDict\n\nfrom ..exrpc import rpclib\nfrom ..exrpc.server import FrovedisServer, set_association, \\\n check_association, do_if_active_association\nfrom ..matrix.dvector import FrovedisDvector\nfrom ..matrix.dvector import FrovedisIntDvector, FrovedisLongDvector\nfrom ..matrix.dvector import FrovedisULongDvector\nfrom ..matrix.dvector import FrovedisFloatDvector, FrovedisDoubleDvector\nfrom ..matrix.dvector import FrovedisStringDvector\nfrom ..matrix.dtype import DTYPE, TypeUtil, get_string_array_pointer\nfrom ..matrix.dense import FrovedisRowmajorMatrix\nfrom ..matrix.dense import FrovedisColmajorMatrix\nfrom ..matrix.crs import FrovedisCRSMatrix\nfrom ..mllib.model_util import ModelID\nfrom .info import df_to_sparse_info\nfrom .frovedisColumn import FrovedisColumn\nfrom .dfoperator import dfoperator\nfrom .dfutil import union_lists, infer_dtype, add_null_column_and_type_cast, \\\n infer_column_type_from_first_notna, get_string_typename, \\\n get_python_scalar_type, check_string_or_array_like, \\\n check_stat_error\nfrom ..utils import deprecated\nfrom pandas.core.common import SettingWithCopyWarning\n\ndef read_csv(filepath_or_buffer, sep=',', delimiter=None,\n header=\"infer\", names=None, index_col=None,\n usecols=None, squeeze=False, prefix=None,\n mangle_dupe_cols=True, dtype=None, na_values=None,\n verbose=False, comment=None, low_memory=True,\n rows_to_see=1024, separate_mb=1024):\n \"\"\"\n loads frovedis dataframe from csv file\n \"\"\"\n\n #TODO: support index_col parameter (currently gets ignored)\n if comment is not None:\n if isinstance(comment, str):\n if len(comment) != 1:\n raise ValueError(\"read_csv: comment should be either \" +\\\n \"a string of unit length or None!\")\n # TODO: remove the below error when \"comment\" support would be added in Frovedis\n raise ValueError(\"read_csv: Frovedis currently doesn't support parameter comment!\")\n else:\n comment=\"\"\n\n if delimiter is None:\n delimiter = sep\n\n if len(delimiter) != 1:\n raise ValueError(\"read_csv: Frovedis currently supports only single \"\n \"character delimiters!\")\n\n if not isinstance(verbose, bool):\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"verbose={0}!\".format(verbose))\n\n if not isinstance(mangle_dupe_cols, bool):\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"mangle_dupe_cols={0}!\".format(mangle_dupe_cols))\n if names:\n if len(np.unique(names)) != len(names):\n raise ValueError(\"read_csv: Duplicate names are not allowed.\")\n\n if na_values is None:\n na_values = ['null', 'NULL', 'nan', '-nan', 'NaN', '-NaN', 'NA', 'N/A', 'n/a']\n elif isinstance(na_values, dict):\n raise ValueError(\"read_csv: Frovedis currently doesn't support \"\\\n \"na_values as dictionary!\")\n else:\n na_values = check_string_or_array_like(na_values, 'read_csv')\n \n if header not in (\"infer\", 0, None):\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"header={0}!\".format(header))\n\n import csv\n with open(filepath_or_buffer) as f:\n reader = csv.reader(f, delimiter=delimiter)\n row1 = next(reader)\n ncols = len(row1)\n\n if ncols == 0:\n raise ValueError(\"read_csv: Frovedis currently doesn't support \"\n \"blank line at beginning!\")\n\n if dtype and isinstance(dtype, dict):\n dtype = {key: np.dtype(value).name for (key,value) in dtype.items()}\n\n add_index = True\n if usecols is not None:\n if all(isinstance(e, int) for e in usecols):\n usecols = np.asarray(usecols, dtype=np.int32)\n if np.min(usecols) < 0 or np.max(usecols) >= ncols:\n raise ValueError(\"read_csv: usecols index is out-of-bound!\")\n else:\n raise ValueError(\"read_csv: currently Frovedis supports only ids \" +\\\n \"for usecols parameter!\")\n else:\n usecols = np.empty(0, dtype=np.int32)\n \n if names is None:\n if header is None:\n if prefix is None:\n names = [str(i) for i in range(0, ncols)]\n elif isinstance(prefix, str):\n names = [prefix + str(i) for i in range(0, ncols)]\n else:\n raise ValueError(\"read_csv: Frovedis doesn't support \"\n \"prefix={0}!\".format(prefix))\n else:\n names = [] #to be infered from 0th line in input csv file\n else:\n if len(usecols) > 0:\n if len(names) == ncols:\n pass\n elif len(names) == len(usecols):\n # if names is given, frovedis expects all column names to be\n # provided. thus populating dummy names for those columns\n # which are not in usecols\n tnames = [\"_c_\" + str(i) for i in range(0, ncols)]\n for i in range(len(usecols)):\n cid = usecols[i]\n tnames[cid] = names[i]\n names = tnames\n else:\n raise ValueError(\"read_csv: Passed header names mismatches usecols\")\n else:\n if len(names) == ncols - 1:\n names = [\"index\"] + names\n add_index = False\n elif len(names) > ncols:\n names = names[:ncols] # TODO: support pandas like NaN cols\n elif len(names) < ncols - 1:\n raise ValueError(\"read_csv: Frovedis currently doesn't support \"\n \"multi-level index loading!\")\n index_col_no = -1\n if index_col is None:\n pass\n elif isinstance(index_col, bool):\n if index_col:\n raise ValueError(\"read_csv: The value of index_col couldn't be 'True'\")\n else:\n # dont use 1st col as index\n if names[0] == \"index\":\n names = names[1:]\n add_index = True\n elif isinstance(index_col, int):\n if index_col < 0 or index_col > (ncols -1 ):\n raise ValueError(\"read_csv: The value for 'index_col' is invalid!\")\n index_col_no = index_col\n if names == []:\n add_index = False\n elif names[0] == \"index\":\n names = names[1:]\n add_index = False\n if len(names) == ncols - 1:\n names.insert(index_col, \"index\") \n #inserted in names, so this is parsed as well \n else:\n raise ValueError(\"read_csv: Frovedis currently supports only bool and int types for index_col !\")\n\n single_dtype = None\n types = []\n partial_type_info = False\n if dtype is None:\n dtype = {}\n types = []\n elif isinstance(dtype, dict):\n if not names:\n partial_type_info = True\n elif not set(names).issubset(set(dtype.keys())):\n partial_type_info = True\n else:\n types = [get_string_typename(dtype[e]) for e in names]\n else:\n # single_dtype\n single_dtype = np.dtype(dtype).name #raise exception if dtype not valid\n if names:\n n = len(names)\n else:\n n = ncols\n if single_dtype == 'bool':\n types = [] # let it be infered at server side\n else:\n types = [get_string_typename(single_dtype)] * n\n\n is_all_bools = single_dtype == 'bool'\n bool_cols = []\n if isinstance(dtype, dict):\n bool_cols = [k for k in dtype if dtype[k] == 'bool']\n\n name_arr = get_string_array_pointer(names)\n type_arr = get_string_array_pointer(types)\n bool_cols_arr = get_string_array_pointer(bool_cols)\n\n # for partial_type_info\n dtype_keys = []\n dtype_vals = []\n if partial_type_info:\n dtype_keys = list(dtype.keys())\n dtype_vals = [get_string_typename(e) for e in dtype.values()]\n dtype_keys_arr = get_string_array_pointer(dtype_keys)\n dtype_vals_arr = get_string_array_pointer(dtype_vals)\n\n na_sz = len(na_values)\n na_ptr = get_string_array_pointer(na_values)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.load_dataframe_from_csv(host, port, \n filepath_or_buffer.encode('ascii'),\n type_arr, name_arr,\n len(type_arr), len(name_arr),\n delimiter.encode('ascii'),\n na_ptr, na_sz,\n comment.encode(\"ascii\"),\n rows_to_see, separate_mb,\n partial_type_info,\n dtype_keys_arr, dtype_vals_arr,\n len(dtype_keys), low_memory, add_index,\n usecols, len(usecols),\n verbose, mangle_dupe_cols, index_col_no,\n bool_cols_arr, len(bool_cols_arr),\n is_all_bools)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n if is_all_bools:\n types = [DTYPE.BOOL] * len(types)\n elif len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n res = FrovedisDataframe().load_dummy(dummy_df[\"dfptr\"], \\\n names[1:], types[1:])\n #TODO: handle index/num_row setting inside load_dummy()\n res.index = FrovedisColumn(names[0], types[0]) #setting index\n res.num_row = dummy_df[\"nrow\"]\n return res\n\nclass DataFrame(object):\n \"\"\"\n DataFrame\n \"\"\"\n\n def __init__(self, df=None, is_series=False):\n \"\"\"\n __init__\n \"\"\"\n self.__fdata = None\n self.__cols = None\n self.__types = None\n self.index = None\n self.is_series = is_series\n if df is not None:\n self.load(df)\n\n def has_index(self):\n \"\"\"\n has_index\n \"\"\"\n return self.index is not None\n\n @set_association\n def load_dummy(self, fdata, cols, types):\n \"\"\"\n load_dummy\n \"\"\"\n self.__fdata = fdata\n self.__cols = cols\n self.__types = types\n for i in range(0, len(cols)):\n cname = cols[i]\n dt = types[i]\n self.__dict__[cname] = FrovedisColumn(cname, dt)\n return self\n\n def show(self):\n \"\"\"\n show\n \"\"\"\n '''\n if self.__fdata is not None:\n (host, port) = FrovedisServer.getServerInstance()\n rpclib.show_frovedis_dataframe(host, port, self.__fdata)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n print(\"\\n\")\n '''\n print(str(self))\n\n def release(self):\n \"\"\"\n to release dataframe pointer from server heap and\n resets after-fit populated attributes to None\n \"\"\"\n self.__release_server_heap()\n if self.__cols is not None:\n for cname in self.__cols:\n del self.__dict__[cname]\n self.__fdata = None\n self.__cols = None\n self.__types = None\n self.index = None\n self.is_series = None\n\n @do_if_active_association\n def __release_server_heap(self):\n \"\"\" releases the dataframe pointer from server heap \"\"\"\n (host, port) = FrovedisServer.getServerInstance()\n rpclib.release_frovedis_dataframe(host, port, self.__fdata)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n def __del__(self):\n \"\"\" destructs a python dataframe object \"\"\"\n self.release()\n\n def is_fitted(self):\n \"\"\" function to confirm if the dataframe is already constructed \"\"\"\n return self.__fdata is not None\n\n @check_association\n def __len__(self):\n \"\"\"\n to be invoked by len() method\n \"\"\"\n #TODO: set this parameter always\n if \"num_row\" not in self.__dict__:\n (host, port) = FrovedisServer.getServerInstance()\n self.num_row = rpclib.get_frovedis_dataframe_length(host, port, \\\n self.__fdata)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return int(self.num_row)\n\n @property\n def ndim(self):\n \"\"\"return dimension in input df\"\"\"\n return 1 if self.is_series else 2 \n\n @ndim.setter\n def ndim(self, val):\n \"\"\"ndim setter\"\"\"\n raise AttributeError(\\\n \"attribute 'ndim' of DataFrame object is not writable\")\n\n @property\n def count(self): # similar to spark dataframe \n \"\"\"return num_row in input df\"\"\"\n return len(self)\n\n @count.setter\n def count(self, val):\n \"\"\"count setter\"\"\"\n raise AttributeError(\\\n \"attribute 'count' of DataFrame object is not writable\")\n\n @property\n @check_association\n def dtypes(self):\n \"\"\"return data types of input df\"\"\"\n dt = {}\n for i in range(len(self.__cols)):\n if self.__types[i] == DTYPE.STRING:\n dt[self.__cols[i]] = \"object\"\n else:\n dt[self.__cols[i]] = \\\n TypeUtil.to_numpy_dtype(self.__types[i]).__name__\n return pd.Series(dt)\n\n @dtypes.setter\n def dtypes(self, val):\n \"\"\"dtypes setter\"\"\"\n raise AttributeError(\\\n \"attribute 'dtypes' of DataFrame object is not writable\")\n\n @property\n @check_association\n def shape(self):\n \"\"\"return shape of input df\"\"\"\n return (len(self), len(self.__cols))\n\n @shape.setter\n def shape(self, val):\n \"\"\"shape setter\"\"\"\n raise AttributeError(\\\n \"attribute 'shape' of DataFrame object is not writable\")\n\n @set_association\n def load(self, df):\n \"\"\"\n load\n \"\"\"\n if len(df) == 0:\n raise ValueError(\"Cannot load an empty pandas dataframe \" +\\\n \"(column types could not be deduced)\")\n if isinstance(df.index, pd.MultiIndex):\n raise ValueError(\"Cannot load a pandas dataframe \" +\\\n \"with multi level index\")\n\n self.release()\n self.num_row = len(df)\n cols = df.columns.tolist()\n self.__cols = cols\n indx_name = df.index.name if df.index.name is not None else \"index\"\n cols = [indx_name] + cols\n size = len(cols)\n types = [0] * size\n dvec = [None] * size\n\n for idx in range(0, size):\n cname = cols[idx]\n if idx == 0:\n val = df.index\n else:\n val = df[cname]\n vtype = val.dtype.name\n if vtype == 'object': # type-infering required to detect string\n vtype = infer_column_type_from_first_notna(df, val, idx == 0)\n #print(cname + \":\" + vtype)\n if vtype == 'int32' or vtype == 'int':\n dt = DTYPE.INT\n dvec[idx] = FrovedisIntDvector(val)\n elif vtype == 'int64' or vtype == 'long':\n dt = DTYPE.LONG\n dvec[idx] = FrovedisLongDvector(val)\n elif vtype == 'uint64':\n dt = DTYPE.ULONG\n dvec[idx] = FrovedisULongDvector(val)\n elif vtype == 'float32' or vtype == 'float':\n dt = DTYPE.FLOAT\n dvec[idx] = FrovedisFloatDvector(val)\n elif vtype == 'float64' or vtype == 'double':\n dt = DTYPE.DOUBLE\n dvec[idx] = FrovedisDoubleDvector(val)\n elif vtype == 'str' or vtype == 'str_':\n dt = DTYPE.STRING\n dvec[idx] = FrovedisStringDvector(val)\n elif vtype == 'bool' or vtype == 'bool_':\n dt = DTYPE.BOOL\n dvec[idx] = FrovedisIntDvector(np.asarray(val, dtype=np.int32))\n else:\n raise TypeError(\"Unsupported column type '%s' in creation of \"\\\n \"frovedis dataframe: \" % (vtype))\n types[idx] = dt\n if idx == 0:\n self.index = FrovedisColumn(cname, dt) \n else:\n self.__dict__[cname] = FrovedisColumn(cname, dt) #For query purpose\n\n col_names = get_string_array_pointer(cols)\n dvec_arr = np.asarray([dv.get() for dv in dvec], dtype=c_long)\n dptr = dvec_arr.ctypes.data_as(POINTER(c_long))\n type_arr = np.asarray(types, dtype=c_short)\n tptr = type_arr.ctypes.data_as(POINTER(c_short))\n self.__types = types[1:]\n\n (host, port) = FrovedisServer.getServerInstance()\n self.__fdata = rpclib.create_frovedis_dataframe(host, port, tptr,\n col_names, dptr, size)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n # dvectors in 'dptr' are already destructed during dataframe\n # construction. thus resetting the metadata to avoid double\n # free issue from server side during destructor calls of the \n # dvectors in 'dptr'\n for dv in dvec:\n dv.reset()\n\n def __getitem__(self, target):\n \"\"\"\n __getitem__\n \"\"\"\n if self.__fdata is not None:\n if isinstance(target, str):\n return self.select_frovedis_dataframe([target])\n elif isinstance(target, list):\n return self.select_frovedis_dataframe(target)\n elif isinstance(target, dfoperator):\n return self.filter_frovedis_dataframe(target)\n elif isinstance(target, slice):\n return self.__filter_slice_range(target)\n else:\n raise TypeError(\"Unsupported indexing input type!\")\n else:\n raise ValueError(\"Operation on invalid frovedis dataframe!\")\n\n @property\n @check_association\n def columns(self):\n \"\"\"returns column list\"\"\"\n return self.__cols\n\n @columns.setter\n @check_association\n def columns(self, newcols):\n \"\"\"renames columns\"\"\"\n if newcols is None or np.isscalar(newcols):\n raise TypeError(\"must be called with a collection of some \"\n \"kind, '%s' was passed\" % (newcols))\n if len(newcols) != len(self.__cols):\n raise ValueError(\"Length mismatch: Expected axis has %d elements\"\n \", new values have %d elements\" \\\n % (len(self.__cols), len(newcols)))\n self.rename(columns=dict(zip(self.__cols, newcols)), inplace=True)\n\n @check_association\n def filter_frovedis_dataframe(self, opt):\n \"\"\" \n filters rows on the basis of given 'opt' condition \n from the input dataframe \n \"\"\"\n ret = DataFrame(is_series=self.is_series)\n ret.index = self.index\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.filter_frovedis_dataframe(host, port, \\\n self.get(), opt.get())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, list(self.__cols), list(self.__types)) \n return ret \n\n @check_association\n def select_frovedis_dataframe(self, targets):\n \"\"\" selects given columns from the input dataframe \"\"\"\n targets = list(check_string_or_array_like(targets, \"select\"))\n is_ser = len(targets) == 1\n ret = DataFrame(is_series=is_ser)\n ret_types = self.__get_column_types(targets)\n ret_cols = list(targets) #targets is a list\n ret.num_row = len(self) \n ret.index = self.index\n\n if self.has_index():\n targets = [self.index.name] + targets\n\n sz = len(targets) \n ptr_arr = get_string_array_pointer(targets)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.select_frovedis_dataframe(host, port, self.get(), \\\n ptr_arr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n return ret \n\n @check_association\n def nsort(self, n, columns, keep='first', is_desc=False):\n \"\"\"\n returns top n sorted rows (in ascending or descending order)\n \"\"\"\n func = \"nlargest\" if is_desc else \"nsmallest\"\n if not isinstance(n, int):\n raise TypeError(\\\n func + \": expected a positive integer for 'n' parameter!\\n\")\n elif n < 0:\n raise ValueError(\\\n func + \": expected a positive integer for 'n' parameter!\\n\")\n\n if not isinstance(keep, str):\n raise TypeError(\\\n func + \": expected a string for 'keep' parameter!\\n\")\n elif keep != \"all\" and keep != \"first\" and keep != \"last\":\n raise ValueError(func + \": supported 'keep' values are 'first', \"\\\n \"'last' and 'all' only! receieved %s.\\n\" % (keep))\n\n sort_by = check_string_or_array_like(columns, func)\n for item in sort_by:\n # TODO: confirm possibility of including index column\n #if item not in self.columns and item != self.index.name:\n if item not in self.columns: \n raise ValueError(func + \": No column named: \" + str(item))\n\n sz = len(sort_by) \n ptr_arr = get_string_array_pointer(sort_by)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_ksort(host, port, self.get(),\n n, ptr_arr, sz, keep.encode('ascii'), \n is_desc)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret = DataFrame(is_series=self.is_series)\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n def nlargest(self, n, columns, keep='first'):\n \"\"\"\n returns top n sorted rows in descending order\n \"\"\"\n return self.nsort(n, columns, keep, is_desc=True)\n\n def nsmallest(self, n, columns, keep='first'):\n \"\"\"\n returns top n sorted rows in ascending order\n \"\"\"\n return self.nsort(n, columns, keep, is_desc=False)\n\n def sort_index(self, axis=0, ascending=True, inplace=False,\n kind='quicksort', na_position='last'):\n \"\"\"\n sort_index\n \"\"\"\n return self.sort_values(by=self.index.name, axis=axis, ascending=ascending, \n inplace=inplace, kind=kind, na_position=na_position)\n\n @check_association\n def sort_values(self, by, axis=0, ascending=True,\n inplace=False, kind='radixsort', na_position='last'):\n \"\"\"\n sort_values\n \"\"\"\n if na_position != \"last\":\n if na_position == \"first\":\n raise ValueError(\"Frovedis currently doesn't support \" \\\n \"na_position='first' !\")\n else:\n raise ValueError(\"invalid na_position: '{}' \".format(na_position))\n\n if axis not in (0, \"index\"):\n if axis in (1, \"columns\"):\n raise ValueError(\"Frovedis currently doesn't support sorting \" \\\n \"the axis = 1 !\")\n else:\n raise ValueError(\"No axis named {} for frovedis dataframe !\"\n .format(axis))\n\n if kind not in [\"radixsort\", \"stable\"]:\n warnings.warn(\"Frovedis currently supports radixsort (stable) \" \\\n \"internally, other 'kind' parameters will be ignored!\")\n\n if inplace:\n raise ValueError(\"Frovedis currently doesn't support inplace \" \\\n \"sorting of dataframes ! \")\n\n sort_by = check_string_or_array_like(by, \"sort\")\n for item in sort_by:\n if item not in self.columns and item != self.index.name:\n raise ValueError(\"sort: No column named: %s\" % str(item))\n\n sz = len(sort_by) \n sort_by_arr = get_string_array_pointer(sort_by)\n \n if type(ascending).__name__ == 'bool':\n orderlist = [ascending] * sz\n sort_order = np.asarray(orderlist, dtype=np.int32)\n elif type(ascending).__name__ == 'list':\n if len(ascending) != sz:\n raise ValueError(\"sort: Length of by and ascending parameters\"\n \" are not matching!\")\n sort_order = np.asarray(ascending, dtype=np.int32)\n else:\n dgt = str(ascending).isdigit()\n if dgt:\n orderlist = [bool(ascending)] * sz\n sort_order = np.asarray(orderlist, dtype=np.int32)\n else:\n raise TypeError(\"sort: Expected: digit|list; Received: \",\n type(ascending).__name__)\n\n ret = DataFrame(is_series=self.is_series)\n ret.index = self.index\n ret.num_row = len(self) \n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.sort_frovedis_dataframe(host, port, self.get(),\\\n sort_by_arr, sort_order, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, list(self.__cols), list(self.__types)) \n return ret \n\n def sort(self, columns=None, axis=0, ascending=True,\n inplace=False, kind='radixsort', na_position='last', **kwargs):\n \"\"\"\n sort_\n \"\"\"\n if not columns:\n raise ValueError(\"Column to be sorted cannot be None!\")\n return self.sort_values(by=columns, axis=axis,\n ascending=ascending,\n inplace=inplace, kind=kind,\n na_position=na_position)\n\n @check_association\n def groupby(self, by=None, axis=0, level=None,\n as_index=True, sort=True, group_keys=True, squeeze=False,\n observed=False, dropna=True):\n \"\"\"\n groupby\n \"\"\"\n from frovedis.dataframe import grouped_df\n if axis != 0:\n raise NotImplementedError(\\\n \"groupby: axis = '%d' is currently not supported!\" % (axis))\n\n if level is not None: \n raise NotImplementedError( \\\n \"groupby: level is currently not supported!\")\n\n g_by = check_string_or_array_like(by, \"groupby\")\n types = self.__get_column_types(g_by) \n if dropna:\n g_df = self.dropna(subset=g_by)\n else:\n g_df = self\n\n sz = len(g_by) \n ptr_arr = get_string_array_pointer(g_by)\n (host, port) = FrovedisServer.getServerInstance()\n fdata = rpclib.group_frovedis_dataframe(host, port, g_df.get(),\n ptr_arr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return grouped_df.FrovedisGroupedDataframe()\\\n .load_dummy(fdata, list(g_by), list(types), \\\n list(self.__cols), list(self.__types))\n def __merge_rename_helper(self, rename_dict):\n \"\"\"\n helper function for renaming columns/index for dataframe\n \"\"\"\n ret = self.rename(rename_dict)\n index_name = self.index.name\n\n if index_name is not None and index_name in rename_dict:\n ret = self.rename_index(rename_dict[index_name])\n\n return ret\n\n # method to evaluate join keys\n def __evaluate_join_condition(self, df_right, left_on, right_on):\n \"\"\"\n __evaluate_join_condition\n \"\"\"\n # assumes left_on, right_on as python list\n if len(left_on) != len(right_on):\n raise ValueError(\"Size of left_on and right_on is\" +\n \" not matched!\")\n #for renaming\n col_dict = {}\n for i in range(len(left_on)):\n if left_on[i] == right_on[i]:\n tmp = right_on[i] + \"_right\"\n col_dict[right_on[i]] = tmp\n right_on[i] = tmp\n df_right = df_right.__merge_rename_helper(col_dict)\n renamed_key = list(col_dict.values()) # [] if no renaming is performed\n\n # for dfopt combining\n sz = len(left_on)\n left_on_arr = get_string_array_pointer(left_on)\n right_on_arr = get_string_array_pointer(right_on)\n\n (host, port) = FrovedisServer.getServerInstance()\n dfopt_proxy = rpclib.get_multi_eq_dfopt(host, port, left_on_arr,\n right_on_arr, sz)\n dfopt = dfoperator(dfopt_proxy)\n return (df_right, dfopt, renamed_key, right_on)\n\n def __get_frovedis_how(self, how):\n pandas_to_frov_how = { \"left\": \"outer\",\n \"inner\": \"inner\" }\n if how not in pandas_to_frov_how:\n raise ValueError(\"Frovedis currently doesn't support how={0}!\".format(how))\n return pandas_to_frov_how[how]\n\n @check_association\n def merge(self, right, on=None, how='inner', left_on=None, right_on=None,\n left_index=False, right_index=False, sort=False,\n suffixes=('_x', '_y'), copy=True,\n indicator=False, join_type='bcast'):\n \"\"\"\n merge\n \"\"\"\n\n right = DataFrame.asDF(right)\n on_index = None\n\n if not isinstance(left_index, bool):\n raise ValueError(\n \"left_index parameter must be of type bool, not \", type(left_index)\n )\n if not isinstance(right_index, bool):\n raise ValueError(\n \"right_index parameter must be of type bool, not\", type(right_index)\n )\n\n if left_on and left_index:\n raise ValueError(\"Can only pass 'left_on' OR 'left_index'\" +\n \" not a combination of both!\")\n elif right_on and right_index:\n raise ValueError(\"Can only pass 'right_on' OR 'right_index'\" +\n \" not a combination of both!\")\n elif on and (left_index or right_index):\n raise ValueError(\"Can only pass 'on' OR 'left_index' and\" +\n \" 'right_index', not a combination of both!\")\n \n # table must have index, if merge-target is index\n if left_index and not self.has_index():\n raise ValueError(\"left table doesn't have index!\\n\")\n if right_index and not right.has_index():\n raise ValueError(\"right table doesn't have index!\\n\")\n\n # index rename for right, if same with left\n if self.has_index() and right.has_index():\n if self.index.name == right.index.name:\n right = right.rename_index(right.index.name + \"_right\")\n reset_index_name = False #rename not required, if both are same\n else:\n # if both table have different names for index,\n # then if merge takes place on both indices i.e., \n # (left_index=right_index=True), resultant table \n # would have generic name for index column\n reset_index_name = True\n\n if left_index and right_index:\n on_index = self.index\n if self.index.name == \"index\": \n #rename not required, if index-name is already generic\n reset_index_name = False \n elif left_index and not right_index:\n on_index = right.index\n reset_index_name = False\n elif right_index and not left_index:\n on_index = self.index\n reset_index_name = False\n\n if on: #if key name is same in both dataframes\n if(left_on) or (right_on):\n raise ValueError(\"Can only pass 'on' OR 'left_on' and\" +\n \" 'right_on', not a combination of both!\")\n left_on = right_on = on\n\n # no of nulls\n n_nulls = sum(x is None for x in (on, right_on, left_on))\n if n_nulls == 3:\n if self is right: \n # Early return: all columns are common => all comlumns are treated as keys\n # returning a copy of self\n ret = self.select_frovedis_dataframe(self.columns)\n ret.reset_index(drop=True, inplace=True)\n return ret\n\n if left_index and right_index:\n left_on, right_on = self.index.name, right.index.name\n elif left_index:\n raise ValueError(\"Must pass right_on or right_index=True\")\n elif right_index:\n raise ValueError(\"Must pass left_on or left_index=True\")\n else:\n common_cols = list(set(self.columns) & set(right.columns))\n if len(common_cols) == 0:\n raise ValueError(\"No common columns to perform merge on.\")\n left_on = right_on = common_cols\n elif left_on and right_index:\n right_on = right.index.name\n elif left_index and right_on:\n left_on = self.index.name\n\n if (left_on and not right_on) or (not left_on and right_on):\n raise ValueError(\"Both left_on and right_on need to be provided.\"+\n \" In case of common keys, use 'on' parameter!\")\n\n if not isinstance(left_on, (tuple, list)):\n left_keys = [left_on]\n else:\n left_keys = list(left_on)\n\n if not isinstance(right_on, (tuple, list)):\n right_keys = [right_on]\n else:\n right_keys = list(right_on)\n\n # right, right_keys may be modified if keys are same ( in __evaluate_join_condition())\n right, dfopt, renamed_keys, right_keys = \\\n self.__evaluate_join_condition(right, left_keys, right_keys)\n\n left_non_key_cols = set(self.__cols) - set(left_keys)\n right_non_key_cols = set(right.__cols) - set(right_keys)\n common_non_key_cols = left_non_key_cols & right_non_key_cols\n \n left_non_key_column_in_right_key = left_non_key_cols & set(right_keys)\n right_non_key_column_in_left_key = right_non_key_cols & set(left_keys)\n\n # if renaming required add suffixes\n df_left = self\n df_right = right\n if len(common_non_key_cols) > 0 \\\n or len(left_non_key_column_in_right_key) > 0 \\\n or len(right_non_key_column_in_left_key) > 0:\n renamed_left_cols = {}\n renamed_right_cols = {}\n lsuf, rsuf = suffixes\n if lsuf == '' and rsuf == '':\n raise ValueError(\"columns overlap but no suffix specified: %s \" \\\n % common_non_key_cols)\n for e in common_non_key_cols:\n renamed_left_cols[e] = e + str(lsuf)\n renamed_right_cols[e] = e + str(rsuf)\n\n for e in left_non_key_column_in_right_key:\n renamed_left_cols[e] = e + str(lsuf)\n\n for e in right_non_key_column_in_left_key:\n renamed_right_cols[e] = e + str(rsuf)\n\n if lsuf != '':\n df_left = self.__merge_rename_helper(renamed_left_cols)\n if rsuf != '':\n df_right = right.__merge_rename_helper(renamed_right_cols)\n\n ret = DataFrame()\n ret_cols = df_left.__cols + df_right.__cols\n ret_types = df_left.__types + df_right.__types\n frov_how = self.__get_frovedis_how(how)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.merge_frovedis_dataframe(host, port, df_left.get(), \\\n df_right.get(), dfopt.get(), \\\n frov_how.encode('ascii'), \\\n join_type.encode('ascii'))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n \n targets = ret.columns\n if renamed_keys:\n for key in renamed_keys:\n if key in targets:\n targets.remove(key)\n\n if on_index:\n index_name = on_index.name\n ret.index = FrovedisColumn(index_name, dtype=on_index.dtype)\n ret = ret.select_frovedis_dataframe(targets)\n if index_name.endswith(\"_right\"):\n index_name = index_name[:-len(\"_right\")]\n ret.rename_index(index_name, inplace=True)\n elif reset_index_name:\n ret.rename_index(\"index\", inplace=True)\n else:\n ret = ret.select_frovedis_dataframe(targets)\n ret = ret.add_index(\"index\")\n\n return ret\n \n # exception at frovedis server: same key is not\n # currently supported by frovedis\n def join(self, right, on, how='inner',\n lsuffix='_left', rsuffix='_right', sort=False, join_type='bcast'):\n \"\"\"\n join\n \"\"\"\n suffix = []\n suffix.append(lsuffix)\n suffix.append(rsuffix)\n if not on:\n raise ValueError(\"Key to join can not be None!\")\n return self.merge(right, on=on, how=how, suffixes=suffix, sort=sort,\n join_type=join_type)\n\n @check_association\n def rename(self, columns, inplace=False):\n \"\"\" returns new dataframe with renamed columns \"\"\"\n if not columns:\n return self\n if not isinstance(columns, dict):\n raise TypeError(\"Expected: dictionary; Received: \",\n type(columns).__name__)\n\n names = list(columns.keys())\n new_names = list(columns.values())\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n ret.index = self.index\n ret.num_row = len(self) \n ret_cols = list(self.__cols)\n ret_types = list(self.__types)\n\n t_names = []\n t_new_names = []\n for i in range(0, len(names)):\n item = names[i]\n new_item = new_names[i]\n if item in ret_cols: # otherwise skipped as in pandas rename()\n if inplace:\n del self.__dict__[item]\n idx = ret_cols.index(item)\n ret_cols[idx] = new_item\n t_names.append(item)\n t_new_names.append(new_item)\n \n sz = len(t_names)\n name_ptr = get_string_array_pointer(t_names)\n new_name_ptr = get_string_array_pointer(t_new_names)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.rename_frovedis_dataframe(host, port, self.get(), \\\n name_ptr, new_name_ptr, \\\n sz, inplace)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n return None if inplace else ret \n\n @check_association\n def rename_index(self, new_name, inplace=False): \n \"\"\" renames index field of self inplace \"\"\"\n if not self.has_index():\n raise ValueError(\"rename_index: no index field for renaming!\")\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n ret.num_row = len(self) \n ret.index = FrovedisColumn(new_name, self.index.dtype)\n ret_cols = list(self.__cols)\n ret_types = list(self.__types)\n\n sz = 1\n name_ptr = get_string_array_pointer([self.index.name])\n new_name_ptr = get_string_array_pointer([new_name])\n\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.rename_frovedis_dataframe(host, port, \\\n self.get(), name_ptr, new_name_ptr, \\\n sz, inplace)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret.load_dummy(proxy, ret_cols, ret_types)\n return None if inplace else ret \n\n def copy(self, deep=True):\n \"\"\"\n copy input dataframe to construct a new dataframe\n \"\"\"\n if not deep:\n raise NotImplementedError(\"copy: shallow-copy is not yet supported!\")\n if self.get() is None: # empty dataframe\n return DataFrame()\n else:\n return self[self.columns]\n\n def get(self):\n \"\"\"\n get proxy of dataframe at server side\n \"\"\"\n return self.__fdata\n\n @staticmethod\n def asDF(df):\n \"\"\"\n asDF\n \"\"\"\n if isinstance(df, DataFrame):\n return df\n elif isinstance(df, pd.DataFrame):\n return DataFrame(df)\n elif isinstance(df, pd.Series):\n return DataFrame(df=pd.DataFrame(df), is_series=True)\n else: \n raise TypeError(\"asDF: invalid dataframe type '%s' \"\n \"is provided!\" % (type(df).__name__))\n\n def __get_column_types(self, columns):\n \"\"\"\n __get_column_types\n \"\"\"\n columns = check_string_or_array_like(columns, \"__get_column_types\")\n sz = len(columns)\n types = [0]*sz\n for i in range(0, sz):\n item = columns[i]\n if item not in self.columns:\n raise ValueError(\"No column named: %s\" % str(item))\n else:\n types[i] = self.__dict__[item].dtype\n return types\n\n # returns python list of strings\n def __get_stat(self, name, columns, types=None):\n \"\"\"\n __get_stat\n \"\"\"\n if len(columns) == 0:\n return []\n if isinstance(types, list) and len(columns) != len(types):\n raise ValueError(\"Size of inputs doesn't match!\")\n if not isinstance(name, str):\n raise TypeError(\"Expected: string; Received: \", type(name).__name__)\n (host, port) = FrovedisServer.getServerInstance()\n sz = len(columns)\n cols_ptr = get_string_array_pointer(columns)\n\n if types:\n type_arr = np.asarray(types, dtype=c_short)\n tptr = type_arr.ctypes.data_as(POINTER(c_short))\n if name == 'min':\n if not types:\n raise ValueError(\"type of target columns is missing for\"\n \" min calculation\")\n ret = rpclib.get_min_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n elif name == 'max':\n if not types:\n raise ValueError(\"type of target columns is missing for\"\n \" max calculation\")\n ret = rpclib.get_max_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n elif name == 'sum':\n if not types:\n raise ValueError(\"type of target columns is missing for\"\n \" sum calculation\")\n ret = rpclib.get_sum_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n elif name == 'std':\n ret = rpclib.get_std_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'sem':\n ret = rpclib.get_sem_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'avg' or name == 'mean':\n ret = rpclib.get_avg_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'count':\n ret = rpclib.get_cnt_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'var':\n ret = rpclib.get_var_frovedis_dataframe(host, port, self.get(),\n cols_ptr, sz)\n elif name == 'median':\n ret = rpclib.get_median_frovedis_dataframe(host, port, self.get(),\n cols_ptr, tptr, sz)\n else:\n raise ValueError(\"Unknown statistics request is encountered!\")\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return ret\n\n def __get_stat_wrapper(self, func_name, columns):\n if self.__fdata is None:\n raise ValueError(\"Operation on invalid frovedis dataframe!\")\n columns = check_string_or_array_like(columns, func_name) \n\n if func_name == \"count\": # uses all columns\n types = self.__get_column_types(columns)\n return self.__get_stat('count', columns, types)\n else:\n numeric_cols, numeric_cols_types = \\\n self.__get_numeric_columns(cols=columns)\n ret = self.__get_stat(func_name, numeric_cols, numeric_cols_types)\n result_dict = dict(zip(numeric_cols, ret))\n return [result_dict.get(col, np.nan) for col in columns]\n\n def __get_numeric_columns(self, cols=None, include_bool=True):\n \"\"\"\n __get_numeric_columns\n \"\"\"\n if cols is not None:\n cols = check_string_or_array_like(cols, \"__get_numeric_columns\")\n types = self.__get_column_types(cols)\n else:\n cols = self.__cols\n types = self.__types\n\n if include_bool:\n non_numeric_types = [DTYPE.STRING]\n else:\n non_numeric_types = [DTYPE.STRING, DTYPE.BOOL]\n\n numeric_cols = []\n numeric_col_types = []\n for i in range(0, len(cols)):\n if types[i] not in non_numeric_types:\n numeric_cols.append(cols[i])\n numeric_col_types.append(types[i])\n return numeric_cols, numeric_col_types\n\n #TODO: support pandas-like input parameters and \n # improve result compatibility\n @check_association\n def describe(self):\n \"\"\"\n describe\n \"\"\"\n cols, types = self.__get_numeric_columns(include_bool=False)\n index = ['count', 'mean', 'median', 'var', 'std', 'sem', 'sum', 'min', 'max']\n return self.__agg_impl(cols, index)\n\n def __agg_impl(self, cols, index):\n \"\"\"\n agg impl\n \"\"\"\n func_ret = []\n for ind in index:\n func_ret.append(self.__get_stat_wrapper(ind, cols))\n ret = pd.DataFrame(func_ret, index=index, columns=cols)\n\n ncols = len(cols)\n types = self.__get_column_types(cols)\n has_max = 'max' in ret.index\n has_min = 'min' in ret.index\n # agg func list has std, avg/mean, then dtype = float64\n if (len(set(index).intersection(set(['mean', 'avg', 'std', \\\n 'var', 'median', 'sem']))) > 0):\n rtypes = [np.float64] * ncols\n else:\n rtypes = [np.int32 if x == DTYPE.BOOL \\\n else TypeUtil.to_numpy_dtype(x) for x in types]\n # here we are type-casting column one-by-one.\n # since some pandas version has issue in casting all\n # target columns with dictionary input for astype()\n # REF: https://github.com/pandas-dev/pandas/issues/21445\n warnings.simplefilter(action=\"ignore\", category=SettingWithCopyWarning)\n for i in range(0, ncols):\n ret[cols[i]] = ret[cols[i]].astype(rtypes[i])\n # special treatement for bool columns\n if types[i] == DTYPE.BOOL:\n if has_max:\n tmp = ret[cols[i]]['max']\n ret[cols[i]]['max'] = True if tmp == 1 else False\n if has_min:\n tmp = ret[cols[i]]['min']\n ret[cols[i]]['min'] = True if tmp == 1 else False\n warnings.simplefilter(action=\"default\", category=SettingWithCopyWarning)\n return ret \n\n @check_association\n def agg(self, func):\n if isinstance(func, str):\n return self.__agg_list([func]).transpose()[func]\n elif isinstance(func, list):\n return self.__agg_list(func)\n elif isinstance(func, dict):\n return self.__agg_dict(func)\n else:\n raise ValueError(\"Unsupported 'func' type : {0}\".format(type(func)))\n\n def __agg_list(self, func):\n return self.__agg_impl(cols=self.columns, index=func)\n\n def __agg_dict(self, func_dict):\n from itertools import chain \n func_dict = dict(func_dict)\n for col in func_dict:\n if isinstance(func_dict[col], str):\n func_dict[col] = [func_dict[col]]\n\n all_cols = list(func_dict.keys())\n all_funcs = list(set(chain.from_iterable(func_dict.values())))\n\n df_all_res = self.__agg_impl(cols=all_cols, index=all_funcs)\n data_dict = {col: {} for col in all_cols}\n\n for col in func_dict:\n for func in func_dict[col]:\n data_dict[col][func] = df_all_res[col][func]\n\n return pd.DataFrame(data_dict)\n\n @check_association\n def to_dict(self, orient=\"dict\", into=dict):\n \"\"\"\n returns dataframe columns as dictionary\n \"\"\"\n if orient not in [\"dict\", \"list\"]:\n raise ValueError(\"to_dict: supported only 'dict' and 'list' \" \\\n \"as for 'orient' parameter!\\n\")\n if into != dict:\n #if not isinstance(into, dict):\n raise ValueError(\\\n \"to_dict: supported only dictionary as per return type!\\n\")\n return self.__to_dict_impl(orient=orient, into=into)\n\n def __get_index_column(self):\n \"\"\" returns index column if present \"\"\"\n if not self.has_index():\n raise ValueError(\"input dataframe doesn't have index column!\\n\")\n\n (host, port) = FrovedisServer.getServerInstance()\n indx_dvec = rpclib.get_frovedis_col(host, port, self.get(),\n self.index.name.encode('ascii'),\n self.index.dtype)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return FrovedisDvector(indx_dvec).to_numpy_array()\n\n def __to_dict_impl(self, orient=\"dict\", into=dict, include_index=True):\n \"\"\"\n helper for to_dict\n \"\"\"\n\n out_data = OrderedDict()\n if orient == \"dict\": # presence of index is must \n if self.has_index():\n indx_arr = self.__get_index_column()\n else:\n indx_arr = np.arange(len(self), dtype=np.int64)\n elif orient == \"list\": \n if include_index and self.has_index(): # extract index, if presents\n out_data[self.index.name] = self.__get_index_column()\n \n else:\n raise ValueError(\"to_dict: supported 'orient' values are \" \\\n \"'dict' and 'list' only!\\n\")\n \n (host, port) = FrovedisServer.getServerInstance()\n for i in range(0, len(self.columns)):\n cc = self.__cols[i]\n tt = self.__types[i]\n dvec = rpclib.get_frovedis_col(host, port, self.get(),\n cc.encode('ascii'), tt)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n col_arr = FrovedisDvector(dvec).to_numpy_array()\n #TODO: fix NULL conversion in case of string-vector; \n #TODO: fix numeric to boolean conversion in case of boolean-vector\n if orient == \"dict\":\n out_data[cc] = dict(zip(indx_arr, col_arr)) # this is very slow...\n else: # list\n out_data[cc] = col_arr\n\n return out_data\n\n @check_association\n def to_pandas_dataframe(self):\n \"\"\"\n returns a pandas dataframe object from frovedis dataframe\n \"\"\"\n res = pd.DataFrame(self.__to_dict_impl(orient=\"list\", \\\n include_index=True))\n\n if self.has_index():\n res.set_index(self.index.name, inplace=True)\n if (self.index.dtype == DTYPE.BOOL):\n res.index = res.index.to_series().replace({0: False, 1: True})\n elif (self.index.dtype == DTYPE.STRING):\n res.index = res.index.to_series().replace({\"NULL\": np.nan})\n\n for col in self.columns:\n # BOOL treatment\n if (self.__dict__[col].dtype == DTYPE.BOOL):\n res[col].replace(to_replace={0: False, 1: True}, inplace=True)\n # NULL treatment for string columns\n elif (self.__dict__[col].dtype == DTYPE.STRING):\n res[col].replace(to_replace={\"NULL\": np.nan}, inplace=True)\n return res\n\n @deprecated(\"Use to_pandas_dataframe() instead!\\n\")\n def to_panda_dataframe(self):\n return self.to_pandas_dataframe()\n\n @check_association\n def to_numpy(self, dtype=None, copy=False, na_value=None):\n \"\"\"\n frovedis dataframe to numpy array conversion\n \"\"\"\n out_data = self.__to_dict_impl(orient=\"list\", include_index=False)\n return np.array(list(out_data.values()), dtype=dtype).T\n\n @property\n def values(self):\n \"\"\"\n frovedis dataframe to numpy array conversion\n \"\"\"\n return self.to_numpy()\n\n @values.setter\n def values(self, val):\n \"\"\"values setter\"\"\"\n raise AttributeError(\\\n \"attribute 'values' of DataFrame object is not writable\")\n\n @check_association\n def to_frovedis_rowmajor_matrix(self, t_cols, dtype=np.float32):\n \"\"\"\n to_frovedis_rowmajor_matrix\n \"\"\"\n for item in t_cols: # implicit checks for iterable on 't_cols'\n if item not in self.__cols:\n raise ValueError(\"No column named: %s\" % str(item))\n sz = len(t_cols)\n cols_ptr = get_string_array_pointer(t_cols)\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_rowmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_rowmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return FrovedisRowmajorMatrix(mat=dmat, dtype=dtype)\n\n @check_association\n def to_frovedis_colmajor_matrix(self, t_cols, dtype=np.float32):\n \"\"\"\n to_frovedis_colmajor_matrix\n \"\"\"\n for item in t_cols: # implicit checks for iterable on 't_cols'\n if item not in self.__cols:\n raise ValueError(\"No column named: %s\" % str(item))\n sz = len(t_cols)\n cols_ptr = get_string_array_pointer(t_cols)\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_colmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_colmajor(host, port, self.get(),\n cols_ptr, sz, DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return FrovedisColmajorMatrix(mat=dmat, dtype=dtype)\n\n @check_association\n def to_frovedis_crs_matrix(self, t_cols, cat_cols,\n dtype=np.float32, #default type: float\n need_info=False):\n \"\"\"\n to_frovedis_crs_matrix\n \"\"\"\n for item in t_cols: # implicit checks for iterable on 't_cols'\n if item not in self.__cols:\n raise ValueError(\"No column named: %s\" % str(item))\n for item in cat_cols: # implicit checks for iterable on 'cat_cols'\n if item not in t_cols:\n raise ValueError(\"target column list doesn't contain\"\n \" categorical column: \", item)\n sz1 = len(t_cols)\n cols_ptr = get_string_array_pointer(t_cols)\n sz2 = len(cat_cols)\n cat_cols_ptr = get_string_array_pointer(cat_cols)\n # getting unique id for info to be registered at server side\n info_id = ModelID.get()\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_crs(host, port, self.get(),\n cols_ptr, sz1,\n cat_cols_ptr, sz2,\n info_id, DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_crs(host, port, self.get(),\n cols_ptr, sz1,\n cat_cols_ptr, sz2,\n info_id, DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n #default at server: size_t\n crs = FrovedisCRSMatrix(mat=dmat, dtype=dtype, itype=np.int64)\n info = df_to_sparse_info(info_id)\n\n if need_info:\n return crs, info\n else:\n info.release()\n return crs\n\n @check_association\n def to_frovedis_crs_matrix_using_info(self, info, dtype=np.float32):\n \"\"\"\n to_frovedis_crs_matrix_using_info\n \"\"\"\n if info.get() is None:\n raise ValueError(\"Operation on invalid frovedis dataframe\"\n \" conversion info!\")\n (host, port) = FrovedisServer.getServerInstance()\n if dtype == np.float32:\n dmat = rpclib.df_to_crs_using_info(host, port, self.get(),\n info.get(), DTYPE.FLOAT)\n elif dtype == np.float64:\n dmat = rpclib.df_to_crs_using_info(host, port, self.get(),\n info.get(), DTYPE.DOUBLE)\n else:\n raise TypeError(\"Supported types: float32/float64; Found: \" \\\n + dtype.__name__)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n #default at server: size_t\n return FrovedisCRSMatrix(mat=dmat, dtype=dtype, itype=np.int64)\n\n def filter(self, items=None, like=None, regex=None, axis=None):\n \"\"\"\n Subset the dataframe rows or columns according to the specified index labels.\n \"\"\"\n # no of keyword args\n nkw = sum(x is not None for x in (items, like, regex))\n # only 1 can be not-None\n if nkw > 1:\n raise TypeError(\n \"Keyword arguments `items`, `like`, or `regex` \"\n \"are mutually exclusive\"\n )\n\n if axis not in (None, 0, 1, 'columns', 'index'):\n raise ValueError(\"filter(): Unsupported axis '%s' is\"+\n \" provided!\" % str(axis))\n\n # default axis = 1 , i.e. column names\n if axis is None or axis == 'columns':\n axis = 1\n elif axis == 0 or axis == 'index':\n raise ValueError(\"filter() on 'index' axis is not supported for\"+\n \"frovedis DataFrame!\")\n\n if items is not None:\n targets = list(items)\n elif like is not None:\n def func(x):\n \"\"\" used for filtering \"\"\"\n return like in x\n targets = list(filter(func, self.__cols))\n elif regex is not None:\n import re\n pattern = re.compile(regex)\n def func(x):\n \"\"\" used for filtering \"\"\"\n return pattern.search(x) is not None\n targets = list(filter(func, self.__cols))\n else:\n raise TypeError(\"Must pass either `items`, `like`, or `regex`\")\n return self.select_frovedis_dataframe(targets)\n\n def apply(self, func, axis=0, raw=False, \\\n result_type=None, args=(), **kwds):\n return self.to_pandas_dataframe()\\\n .apply(func, axis, raw, result_type, args)\n\n @check_association\n def isna(self):\n ncol = len(self.__cols)\n cols_ptr = get_string_array_pointer(self.__cols)\n (host, port) = FrovedisServer.getServerInstance()\n proxy = rpclib.isnull_frovedis_dataframe(host, port, self.get(), \\\n cols_ptr, ncol, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame()\n ret.num_row = len(self)\n ret.index = self.index\n ret_cols = list(self.__cols)\n ret_types = [DTYPE.BOOL]*len(self)\n ret.load_dummy(proxy, ret_cols, ret_types)\n if not self.has_index():\n ret.add_index(\"index\")\n return ret\n\n def isnull(self):\n return self.isna()\n\n @check_association\n def drop_duplicates(self, subset=None, keep='first', inplace=False, \\\n ignore_index=False):\n \"\"\" \n drops duplicate rows for specified columns (None: all columns).\n \"\"\"\n if subset is None:\n targets = self.columns # for all columns by default\n else: # must be an iterable\n targets = []\n for col in np.unique(subset): # handling duplicate columns\n if col in self.__cols:\n targets.append(col)\n else:\n raise KeyError(\"Index[\" + col + \"] is not found!\")\n\n if keep != 'first' and keep != 'last':\n raise ValueError(\"drop_duplicates: currently supports only \" \\\n \"'first' or 'last' as for 'keep' parameter!\")\n sz = len(targets)\n targets_ptr = get_string_array_pointer(targets)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.drop_frovedis_duplicate_rows(host, port, \\\n self.get(), targets_ptr, sz, \\\n keep.encode('ascii'))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret = self if inplace else DataFrame()\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n if ignore_index:\n ret.reset_index(drop=True, inplace=True)\n return None if inplace else ret\n \n def drop(self, labels=None, axis=0, index=None, columns=None, \\\n level=None, inplace=False, errors='raise'):\n \"\"\" drops specified labels from rows or columns. \"\"\"\n if columns is not None:\n ret = self.drop_cols(targets=columns, inplace=inplace)\n elif index is not None:\n ret = self.drop_rows(targets=index, inplace=inplace)\n else:\n if labels is None:\n raise TypeError(\"drop() takes at least 2 arguments (1 given)\")\n if axis == 0:\n ret = self.drop_rows(targets=labels, inplace=inplace)\n elif axis == 1:\n ret = self.drop_cols(targets=labels, inplace=inplace)\n else:\n raise ValueError(\"drop(): No axis named %d for \" \\\n \"object type %s\" % (axis, self.__class__))\n return ret \n \n @check_association\n def drop_cols(self, targets, inplace=False):\n \"\"\" drops specified columns from input dataframe. \"\"\"\n targets = check_string_or_array_like(targets, \"drop\")\n\n if inplace:\n for item in targets:\n try:\n idx = self.__cols.index(item)\n self.__cols.pop(idx)\n self.__types.pop(idx)\n del self.__dict__[item]\n except ValueError as ve: #item might not be present in col-list\n raise ValueError(\"drop: No column named: %s\" % str(item))\n\n sz = len(targets)\n targets_ptr = get_string_array_pointer(targets)\n (host, port) = FrovedisServer.getServerInstance()\n rpclib.drop_frovedis_dataframe_columns(host, port, \\\n self.get(), targets_ptr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n else:\n cols = list(self.__cols)\n for item in targets:\n if item not in cols:\n raise ValueError(\"drop: No column named: %s\" % str(item))\n else:\n cols.remove(item)\n return self[cols] # just select the required columns\n\n @check_association\n def drop_rows(self, targets, inplace=False):\n \"\"\" drops specified columns from input dataframe. \"\"\"\n if not self.has_index():\n raise ValueError(\"drop(): input dataframe doesn't \" \\\n \"have any index column!\")\n\n if isinstance(targets, str):\n targets = [targets]\n if isinstance(targets, numbers.Number):\n targets = [targets]\n elif isinstance(targets, Iterable):\n targets = np.unique(targets)\n else:\n raise ValueError(\"drop: given indices must be an iterable!\")\n\n sz = len(targets)\n dtype = self.index.dtype\n index_col = self.index.name.encode('ascii')\n (host, port) = FrovedisServer.getServerInstance()\n\n if dtype == DTYPE.INT:\n targets = np.asarray(targets, dtype=np.int32)\n targets_ptr = targets.ctypes.data_as(POINTER(c_int))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_int(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.LONG:\n targets = np.asarray(targets, dtype=np.int64)\n targets_ptr = targets.ctypes.data_as(POINTER(c_long))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_long(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.ULONG:\n targets = np.asarray(targets, dtype=np.uint)\n targets_ptr = targets.ctypes.data_as(POINTER(c_ulong))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_ulong(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.FLOAT:\n targets = np.asarray(targets, dtype=np.float32)\n targets_ptr = targets.ctypes.data_as(POINTER(c_float))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_float(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.DOUBLE:\n targets = np.asarray(targets, dtype=np.float64)\n targets_ptr = targets.ctypes.data_as(POINTER(c_double))\n dummy_df = rpclib.drop_frovedis_dataframe_rows_double(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n elif dtype == DTYPE.STRING:\n targets_ptr = get_string_array_pointer(targets)\n dummy_df = rpclib.drop_frovedis_dataframe_rows_str(host, port, \\\n self.get(), targets_ptr, sz, \\\n index_col)\n else:\n raise TypeError(\\\n \"drop(): Unsupported index column dtype is detected!\")\n\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret = self if inplace else DataFrame()\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return None if inplace else ret\n\n def __get_dvec(self, dtype, val):\n \"\"\"\n get dvector from numpy array\n \"\"\"\n dvec_constructor_map = { DTYPE.INT: FrovedisIntDvector,\n DTYPE.LONG: FrovedisLongDvector,\n DTYPE.ULONG: FrovedisULongDvector,\n DTYPE.FLOAT: FrovedisFloatDvector,\n DTYPE.DOUBLE: FrovedisDoubleDvector,\n DTYPE.STRING: FrovedisStringDvector,\n DTYPE.BOOL: FrovedisIntDvector\n }\n if dtype not in dvec_constructor_map:\n raise ValueError(\"Unsupported dtype for creating dvector: {0}!\\n\"\n .format(dtype))\n if dtype == DTYPE.BOOL:\n val = np.array(val).astype(np.int32)\n res = dvec_constructor_map[dtype](val)\n return res\n\n def __append_column(self, col_name, data_type, data, position=None,\n drop_old=False):\n if col_name is None:\n raise ValueError(\"cannot label index with a null key\")\n elif not isinstance(col_name, str):\n raise TypeError(\"expected a string parameter for 'col_name'! \"\n \"received: '%s'\" % (type(col_name).__name__))\n\n if position is None:\n pos = -1\n elif isinstance(position, int):\n if position < 0 or position > (len(self.columns)):\n raise ValueError(\"Invalid position for appending column : {} !\"\n .format(position))\n if self.has_index():\n pos = position + 1 # 0 is reserved for index column\n else:\n pos = position\n else:\n raise TypeError(\"Invalid type for position, for appending \"\n \"column: {} !\".format(position))\n\n data_type = TypeUtil.to_id_dtype(data_type)\n is_bool = (data_type == DTYPE.BOOL)\n dvec = self.__get_dvec(data_type, data)\n (host, port) = FrovedisServer.getServerInstance()\n df_proxy = -1\n if self.__fdata:\n df_proxy = self.get()\n dummy_df = rpclib.df_append_column(host, port, df_proxy,\n col_name.encode(\"ascii\"),\n data_type, dvec.get(),\n pos, drop_old)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n # dvector 'dvec' is already destructed during append column.\n # thus resetting the metadata to avoid double free issue from\n # server side during destructor call of the dvector 'dvec'\n dvec.reset()\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n if is_bool:\n ind = names.index(col_name)\n types[ind] = DTYPE.BOOL\n\n bool_cols = set([self.__cols[i] for i in range(len(self.__types)) \\\n if self.__types[i] == DTYPE.BOOL])\n if len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n self.num_row = dummy_df[\"nrow\"]\n if self.has_index() or \\\n df_proxy == -1: # empty dataframe case: new index column is added\n self.index = FrovedisColumn(names[0], types[0]) #setting index\n self.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n self.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n return self\n\n def __get_dtype_name(self, arr): #TODO: improve\n if arr.dtype.name != 'object':\n if arr.dtype.char in (\"U\", \"S\"):\n return \"str\"\n else:\n return arr.dtype.name\n\n # if dtype is object\n arr_without_nan = np.array(list(filter(lambda x: x == x, arr)))\n if arr_without_nan.dtype.name != 'object':\n if arr_without_nan.dtype.char in (\"U\", \"S\"):\n return \"str\"\n else:\n return arr_without_nan.dtype.name\n elif all(isinstance(e, str) for e in arr_without_nan):\n return \"str\"\n else:\n # mixed dtypes\n raise ValueError(\"Cannot convert the values for the given data! \",\n arr)\n\n return res\n\n def __setitem__(self, key, value):\n \"\"\"\n Interface for appending column into DataFrame\n \"\"\"\n if key is None:\n raise ValueError(\"cannot label index with a null key\")\n elif isinstance(key, str):\n key = [key]\n elif not isinstance(key, list):\n raise TypeError(\"__setitem__: supported types for 'key' parameter \"\n \"are either string or list! received: '%s'\"\n % (type(key).__name__))\n\n if isinstance(value, (DataFrame, pd.DataFrame)):\n self.copy_column(value, names_as=key, inplace=True) \n else:\n if np.isscalar(value):\n if self.__fdata is None:\n raise ValueError(\"__setitem__: Frovedis currently doesn't \"\n \"support adding column with scalar \"\n \"values on empty dataframe!\")\n is_imax = (value == np.iinfo(np.int32).max)\n value = [value] * len(self)\n if is_imax: # check to avoid long array construction by default\n value = np.asarray(value, dtype=np.int32)\n else:\n value = np.asarray(value) # deduce type\n elif isinstance(value, (list, pd.Series, np.ndarray)):\n value = np.asarray(value)\n value = np.array(list(map(lambda x: np.nan if x is None else x, value)))\n if value.ndim != 1:\n raise ValueError(\\\n \"array is not broadcastable to correct shape\")\n if self.__fdata is not None and len(value) != len(self):\n raise ValueError(\"Length of values (%d) does not match \" \\\n \"with length of index (%d)\" % (len(value), len(self)))\n else:\n raise ValueError(\"__setitem__: Given column data type '{}' \"\n \"is not supported!\".format(type(value)))\n\n col_dtype = np.dtype(self.__get_dtype_name(value))\n for k in key:\n drop_old = False\n if self.__fdata and k in self.columns:\n drop_old = True\n self = self.__append_column(k, col_dtype, value, None, drop_old)\n return self\n\n def insert(self, loc, column, value, allow_duplicates=False):\n \"\"\"\n Insert column into DataFrame at specified location.\n \"\"\"\n if allow_duplicates == True: #TODO: allow it\n raise ValueError(\"insert: Frovedis does not support duplicate \"\n \"column names !\")\n\n if np.isscalar(value):\n if self.__fdata is None:\n raise ValueError(\"insert: Frovedis currently doesn't \"\n \"support adding column with scalar values \"\n \"on empty dataframe!\")\n is_imax = (value == np.iinfo(np.int32).max)\n value = [value] * len(self)\n if is_imax: # check to avoid long array construction by default\n value = np.asarray(value, dtype=np.int32)\n else:\n value = np.asarray(value) # deduce type\n elif isinstance(value, (list, pd.Series, np.ndarray)):\n value = np.asarray(value)\n value = np.array(list(map(lambda x: np.nan if x is None else x, value)))\n if value.ndim != 1:\n raise ValueError(\"array is not broadcastable to correct shape\")\n if self.__fdata is not None and len(value) != len(self):\n raise ValueError(\\\n \"Length of values does not match length of index\")\n else:\n raise ValueError(\"insert: Given column data type '{}' is \"\n \"not supported!\".format(type(value)))\n\n col_dtype = np.dtype(self.__get_dtype_name(value))\n if self.__fdata is None:\n if loc != 0: #insert in empty df, allowed loc = 0 only\n raise IndexError(\"insert: index '{}' is out of bounds for the \"\n \"given dataframe!\".format(loc))\n self = self.__append_column(column, col_dtype, value)\n else:\n if column in self.columns:\n raise ValueError(\"insert: The given column '{}' already exists !\"\n .format(column))\n self = self.__append_column(column, col_dtype, value, loc)\n return self\n\n @check_association\n def update_index(self, value, key=None, \\\n verify_integrity=False, inplace=False):\n \"\"\"\n updates/sets index values: pandas-like df.index = [...]\n \"\"\"\n if inplace: # copy may still take place, if self needs materialize \n ret = self\n else:\n ret = self.copy()\n \n if not isinstance(value, Iterable):\n raise TypeError(\"given index value must be an iterable!\")\n if verify_integrity:\n if len(np.unique(value)) != len(value):\n raise ValueError(\"given index values are not unique!\")\n\n col_data = np.asarray(value)\n col_dtype = self.__get_dtype_name(col_data)\n\n if ret.has_index():\n if key is not None: #rename required\n if ret.index.name != key: \n ret.rename_index(key, inplace=True) \n drop_old = True # existing index column will be dropped\n position = None # adds given column in same position (as in existing index)\n else:\n if key is None:\n key = \"index\" # default name to index-column\n drop_old = False # no index column to drop\n position = 0 # adds given column as index in 0th position\n ret = ret.__append_column(key, np.dtype(col_dtype), col_data, \\\n position, drop_old)\n return None if inplace else ret\n\n #TODO: support drop=False, multi-level index\n @check_association\n def set_index(self, keys, drop=True, append=False,\n inplace=False, verify_integrity=False): \n \"\"\" sets the index column of self \"\"\"\n if not drop:\n raise NotImplementedError(\"set_index: currently frovedis \" \\\n \"doesn't support drop=False!\")\n\n if not isinstance(keys, list):\n keys = [keys]\n \n # multi-level index case\n if append or len(keys) > 1:\n raise NotImplementedError(\"set_index: currently frovedis \" \\\n \"doesn't support multi-level index!\")\n\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n if isinstance(keys[0], str): # keys = [\"colname\"]\n new_index_name = keys[0] \n cur_index_name = self.index.name if self.has_index() else \"\"\n if not new_index_name in ret.__cols:\n raise KeyError(\"set_index: '%s' key does not found in \" \\\n \"existing columns!\" % (new_index_name))\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_set_index(host, port, ret.get(), \\\n cur_index_name.encode(\"ascii\"), \\\n new_index_name.encode(\"ascii\"), \\\n verify_integrity)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) # with new index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n elif isinstance(keys[0], Iterable): # keys = [[1,2,3,4]]\n k = np.asarray(keys[0])\n if k.ndim != 1:\n raise ValueError(\"set_index: expected a one-dimensional key!\")\n ret.update_index(k, key=\"index\", \\\n verify_integrity=verify_integrity, inplace=True)\n else:\n raise TypeError(\"set_index: unknown type of 'keys' found!\")\n return None if inplace else ret \n\n @check_association\n def reset_index(self, drop=False, inplace=False): #TODO: support other params\n \"\"\" resets the index column of self \"\"\"\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n if ret.has_index():\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_reset_index(host, port, ret.get(), \\\n drop)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n bool_cols = set([self.__cols[i] for i in range(len(self.__types)) \\\n if self.__types[i] == DTYPE.BOOL])\n if len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n ret.index = FrovedisColumn(names[0], types[0]) # with new index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret = ret.add_index(\"index\")\n return None if inplace else ret\n\n @check_association\n def copy_index(self, from_df, inplace=False, overwrite=True): \n \"\"\" copies index column from 'from_df' to self \"\"\"\n from_df = DataFrame.asDF(from_df)\n if not from_df.has_index():\n raise ValueError(\"from_df doesn't have any index column!\")\n\n if self.has_index():\n if not overwrite and from_df.index.name == self.index.name:\n raise ValueError(\"input dataframe already has an index \"\\\n \"column with same name!\")\n\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_copy_index(host, port, ret.get(), from_df.get(), \\\n from_df.index.name.encode(\"ascii\"), \\\n from_df.index.dtype)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return None if inplace else ret\n\n def copy_column(self, from_df, names_as=None, inplace=False): \n \"\"\" \n copies all columns from 'from_df' to self. if 'names_as' is given, \n copied columns would be renamed based on 'names_as'\n \"\"\"\n names = list(from_df.columns)\n if names_as is None:\n names_as = names\n elif isinstance(names_as, str):\n names_as = [names_as]\n elif not isinstance(names_as, list):\n raise TypeError(\"copy: supported types for 'names_as' parameter \"\n \"is either string or list! Received '%s' \"\n % (type(names_as).__name__))\n\n if len(names) != len(names_as):\n raise ValueError(\"Columns must be same length as key\")\n \n from_df = DataFrame.asDF(from_df)\n types = np.asarray(from_df.get_types(), dtype=c_short)\n sz = len(types)\n names_arr = get_string_array_pointer(names)\n names_as_arr = get_string_array_pointer(names_as)\n types_arr = types.ctypes.data_as(POINTER(c_short))\n\n if inplace: # copy may still take place, if self needs materialize\n ret = self\n else:\n ret = self.copy()\n\n if ret.__fdata is None: # self is empty DataFrame\n ret.__fdata = -1\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_copy_column(host, port, ret.get(), \\\n from_df.get(), names_arr, \\\n names_as_arr, types_arr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return None if inplace else ret\n\n @check_association\n def add_index(self, name): # behavior: inplace=True\n \"\"\" adds index column to self \"\"\"\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_add_index(host, port, self.get(),\n name.encode(\"ascii\"))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n bool_cols = set([self.__cols[i] for i in range(len(self.__types)) \\\n if self.__types[i] == DTYPE.BOOL])\n if len(bool_cols) > 0:\n for i in range(len(names)):\n if names[i] in bool_cols:\n types[i] = DTYPE.BOOL\n\n self.index = FrovedisColumn(names[0], types[0]) #setting index\n self.num_row = dummy_df[\"nrow\"]\n self.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return self\n\n @check_association\n def astype(self, dtype, copy=True, errors='raise', \n check_bool_like_string=False):\n \"\"\" \n Casts a frovedis DataFrame object to a specified dtype \n\n check_bool_like_string: added parameter; if True, can cast string column\n having bool like case-insensitive strings (True, False, yes, No, \n On, Off, Y, N, T, F) to boolean columns\n \"\"\"\n t_cols = []\n t_dtypes = []\n if isinstance (dtype, (str, type)):\n numpy_dtype = np.dtype(dtype)\n t_cols = list(self.columns)\n t_dtypes = [TypeUtil.to_id_dtype(numpy_dtype)] * len(t_cols)\n elif isinstance (dtype, dict): # might include index as well\n for k, v in dtype.items():\n if k in self.columns or \\\n (self.has_index() and k == self.index.name):\n t_cols.append(k)\n t_dtypes.append(TypeUtil.to_id_dtype(np.dtype(v)))\n else:\n raise TypeError(\"astype: supports only string, numpy.dtype \" \\\n \"or dict object as for 'dtype' parameter!\")\n\n ret = self.copy() # always returns a new dataframe (after casting)\n (host, port) = FrovedisServer.getServerInstance()\n t_cols_ptr = get_string_array_pointer(t_cols)\n type_arr = np.asarray(t_dtypes, dtype=c_short)\n t_dtypes_ptr = type_arr.ctypes.data_as(POINTER(c_short))\n dummy_df = rpclib.df_astype(host, port, ret.get(), t_cols_ptr, \\\n t_dtypes_ptr, len(t_cols), \\\n check_bool_like_string)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n \n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n for i in range(0, len(t_dtypes)):\n if t_dtypes[i] == DTYPE.BOOL:\n col = t_cols[i]\n ind = names.index(col) \n types[ind] = DTYPE.BOOL\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n return ret\n\n @check_association\n def append(self, other, ignore_index=False, verify_integrity=False,\n sort=False):\n if isinstance(other, DataFrame):\n other = [other]\n is_frov_df = [True]\n elif isinstance(other, pd.DataFrame):\n other = [DataFrame.asDF(other)]\n is_frov_df = [False]\n elif isinstance(other, list):\n is_frov_df = [isinstance(e, DataFrame) for e in other]\n other = [DataFrame.asDF(e) for e in other]\n else:\n raise ValueError(\"append: unsupported type '%s' for \"\n \"'other'!\" % (type(other).__name__))\n \n dfs = [self] + other\n is_frov_df = [True] + is_frov_df # prepending [True]; self is DataFrame\n res_names = [self.columns] \n for e in other:\n res_names.append(e.columns)\n res_names = union_lists(res_names)\n res_dtypes = [infer_dtype(dfs, col) for col in res_names]\n astype_input = dict(zip(res_names, res_dtypes))\n #print(astype_input)\n dfs = add_null_column_and_type_cast(dfs, is_frov_df, astype_input)\n\n # preserving column order as in self, if not to be sorted\n res_names = sorted(dfs[0].columns) if sort else dfs[0].columns\n all_cols = [dfs[0].index.name] + res_names # adding index\n proxies = np.asarray([e.get() for e in dfs[1:]]) # default dtype=long\n proxies_ptr = proxies.ctypes.data_as(POINTER(c_long))\n verify_integrity = False if ignore_index else verify_integrity\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_union(host, port, dfs[0].get(), \\\n proxies_ptr, len(proxies), \\\n get_string_array_pointer(all_cols), \\\n len(all_cols), verify_integrity)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n for c, t in astype_input.items():\n if t == np.bool:\n # searching index, since dictionary items might not be ordered\n ind = names.index(c) \n types[ind] = DTYPE.BOOL\n res = DataFrame().load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n res.index = FrovedisColumn(names[0], types[0]) #setting index\n res.num_row = dummy_df[\"nrow\"]\n if ignore_index:\n res.reset_index(inplace=True, drop=True)\n return res\n\n @check_association\n def __set_col_order(self, new_cols):\n if not isinstance(new_cols, list):\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must be provided as list of strings!\")\n else:\n check = all([ isinstance(e, str) for e in new_cols ] )\n if not check:\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must be provided as list of strings!\")\n current_col_order = self.columns\n if self.has_index():\n current_col_order = [self.index.name] + current_col_order\n\n if len(current_col_order) != len(new_cols):\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must have same number of columns as the dataframe!\")\n\n if set(current_col_order) != set(new_cols):\n raise ValueError(\"__set_col_order: The new column order to be set\"\n \" must have same column names as the dataframe!\")\n\n sz = len(new_cols)\n new_cols_ptr = get_string_array_pointer(new_cols)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_set_col_order(host, port, self.get(),\n new_cols_ptr, sz)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n\n self.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n self.index = FrovedisColumn(names[0], types[0]) #setting index\n self.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n self.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n return self\n\n def get_types(self):\n return self.__types\n\n def get_dtype(self, colname):\n \"\"\"\n returns numpy_dtype of given column, \n in case presents in (self.index.name or self.columns).\n otherwise, raises ValueError\n \"\"\"\n if self.has_index() and colname == self.index.name:\n ret = TypeUtil.to_numpy_dtype(self.index.dtype)\n elif colname in self.columns:\n ret = TypeUtil.to_numpy_dtype(self.__dict__[colname].dtype)\n else:\n raise ValueError(\"column not found: '%s'\" % (colname))\n return ret\n\n @check_association\n def fillna(self, value=None, method=None, axis=None, \n inplace=False, limit=None, downcast=None):\n \"\"\" \n replaces nulls in each column with given value\n \"\"\"\n if method is not None:\n raise NotImplementedError(\"fillna: currently doesn't support \"\n \"method: '%s'\" % method)\n\n if limit is not None:\n raise NotImplementedError(\"fillna: currently doesn't support \"\n \"limit: '%d'\" % limit)\n\n if downcast is not None:\n raise NotImplementedError(\"fillna: currently doesn't support \"\n \"downcasting!\")\n\n if axis is None:\n axis = 1 # columns\n elif axis not in (1, 'columns'):\n raise NotImplementedError(\"fillna: can only be performed \"\\\n \"on axis=1 (columns)\")\n\n if value is None: \n raise ValueError(\"fillna: must specify a value\")\n elif value is np.nan:\n return None if inplace else self.copy() # no need for any replacement\n elif not np.isscalar(value):\n raise NotImplementedError(\"fillna: curreently supports only \"\\\n \"scalar values for 'value' parameter, \"\\\n \"received: '%s'\" % type(value).__name__)\n value = str(value)\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_fillna(host, port, \\\n self.get(), value.encode('ascii'), \\\n self.has_index())\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return None if inplace else ret\n\n # optimized implementation for query like \"self.isna().sum(axis=0)\"\n @check_association\n def countna(self, axis=0):\n \"\"\" counts number of missing values in the given axis \"\"\"\n if axis not in [0, 1, \"index\", \"columns\"]:\n raise ValueError(\"No axis named '%s' for DataFrame object\" % str(axis))\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_countna(host, port, self.get(), \\\n axis, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def dropna(self, axis=0, how='any', thresh=None, subset=None, inplace=False):\n \"\"\" drops rows/columns having null values\"\"\"\n if inplace:\n ret = self\n else:\n ret = DataFrame(is_series=self.is_series)\n\n if thresh is None:\n thresh = np.iinfo(np.uint).max\n elif not isinstance(thresh, int):\n raise ValueError(\\\n \"dropna: expected an integer value for 'thresh' parameter!\\n\")\n\n (host, port) = FrovedisServer.getServerInstance()\n if axis == 0: # dropna by rows (extraction subset: column names)\n if subset is None: \n subset = self.columns\n sz = len(subset)\n targets_ptr = get_string_array_pointer(subset)\n dummy_df = rpclib.df_dropna_by_rows(host, port, \\\n self.get(), targets_ptr, sz, \\\n how.encode('ascii'), thresh)\n elif axis == 1: # dropna by cols (extraction subset: index values)\n if not self.has_index():\n raise ValueError(\n \"dropna: input dataframe doesn't have an index column!\")\n index_nm = self.index.name.encode('ascii')\n if subset is None:\n subset = np.asarray([], dtype=np.int32) # int32: dummy type\n sz = len(subset)\n targets_ptr = subset.__array_interface__['data'][0]\n dummy_df = rpclib.df_dropna_by_cols_with_numeric_icol( \\\n host, port, \\\n self.get(), index_nm, targets_ptr, sz, \\\n how.encode('ascii'), thresh, DTYPE.INT)\n else:\n tt = self.index.dtype\n subset = np.asarray(subset, dtype=TypeUtil.to_numpy_dtype(tt))\n sz = len(subset)\n if tt != DTYPE.STRING:\n targets_ptr = subset.__array_interface__['data'][0]\n dummy_df = rpclib.df_dropna_by_cols_with_numeric_icol( \\\n host, port, \\\n self.get(), index_nm, targets_ptr, sz, \\\n how.encode('ascii'), thresh, tt)\n else:\n targets_ptr = get_string_array_pointer(subset)\n dummy_df = rpclib.df_dropna_by_cols_with_string_icol( \\\n host, port, \\\n self.get(), index_nm, targets_ptr, sz, \\\n how.encode('ascii'), thresh)\n else:\n raise ValueError(\\\n \"dropna: Unsupported axis parameter: '%d'\" % (axis))\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names[0:], types[0:])\n ret.num_row = dummy_df[\"nrow\"]\n return None if inplace else ret\n\n @check_association\n def __binary_operator_impl(self, other, op_type, \\\n axis='columns', level=None, \n fill_value=None, is_rev=False):\n \"\"\" \n implements binary opeartions (+, -, *, /, //, %) of \n two dataframes invoking server side operations \n \"\"\"\n if not self.has_index():\n raise TypeError(op_type + \\\n \": input dataframe must have index column!\")\n\n if self.get() is None:\n raise ValueError(op_type + \": invoked on empty dataframe!\")\n\n if DTYPE.STRING in self.get_types(): \n raise NotImplementedError(op_type + \\\n \": table contains string column. Arithmetic operations \"\\\n \"on string column is not supported currently!\")\n \n if axis not in (1, 'columns'):\n raise NotImplementedError(op_type + \\\n \": can only be performed on axis=1 (columns)\")\n\n if fill_value is None or fill_value is np.nan:\n fillv = \"NULL\"\n fillv_dt = \"none\"\n elif np.isscalar(fill_value):\n fillv = str(fill_value)\n fillv_dt = get_python_scalar_type(fill_value)\n else:\n raise NotImplementedError(op_type + \\\n \": supports either None or scalar as for 'fill_value', \"\\\n \"received: %s\" % (fill_value))\n\n if np.isscalar(other):\n if not isinstance(other, (numbers.Number, np.integer, \\\n np.float32, np.float64)): \n raise TypeError(op_type + \\\n \": supported type of 'other' parameter is either DataFrame \"\\\n \"or numbers. Received: '%s'\" % type(other).__name__)\n immed = True\n immed_val = str(other)\n immed_dt = get_python_scalar_type(other)\n is_series = self.is_series\n elif isinstance(other, (list, np.ndarray)):\n other = np.asarray(other)\n is_numeric = all([isinstance(e, numbers.Number) for e in other])\n if not is_numeric:\n raise NotImplementedError(op_type + \\\n \": array-like other contains non-numeric values!\")\n if other.ndim != 1:\n raise ValueError(op_type + \\\n \": multi-dimensional array-like 'other' is not supported!\")\n # below implementation is according to axis = 1\n nrow = len(self)\n ncol = len(self.columns)\n if ncol == 1:\n if len(other) != nrow:\n raise ValueError(op_type + \": Unable to coerce to Series,\" \\\n \" length must be %d: given %d\"\n % (nrow, len(other)))\n other = DataFrame(pd.DataFrame(other, columns=self.columns))\n else:\n if len(other) != ncol:\n raise ValueError(op_type + \": Wrong number of items \" \\\n \"passed %d, placement implies %d\" \\\n % (len(other), ncol))\n tmp_df = pd.DataFrame()\n for i in range(0, ncol):\n tmp_df[self.columns[i]] = [other[i]] * nrow\n other = DataFrame(tmp_df)\n immed = False\n is_series = False\n other.copy_index(self, inplace=True, overwrite=True)\n else:\n other = DataFrame.asDF(other)\n if other.get() is None:\n raise ValueError(op_type + \": right table is empty!\")\n if DTYPE.STRING in other.get_types(): \n raise NotImplementedError(op_type + \\\n \": right table contains string column. Arithmetic operations \"\\\n \"on string column is not supported currently!\")\n immed = False\n is_series = self.is_series and other.is_series\n \n (host, port) = FrovedisServer.getServerInstance()\n # nan values can be generated during pow, div, mod operations\n # and pandas treats nan values as null\n if op_type in (\"pow\", \"fdiv\", \"idiv\", \"mod\"):\n nan_is_null = True\n else:\n nan_is_null = False \n \n if immed:\n # any operation with immediate value as nan would produce nan\n if other is np.nan:\n nan_is_null = True\n dummy_df = rpclib.df_immed_binary_operation(host, port, \\\n self.get(), immed_val.encode('ascii'), \\\n immed_dt.encode('ascii'), \\\n op_type.encode('ascii'), is_rev, nan_is_null)\n else:\n if is_rev:\n left, right = other, self\n else:\n left, right = self, other\n dummy_df = rpclib.df_binary_operation(host, port, left.get(), \\\n right.get(), is_series, fillv.encode('ascii'), \\\n fillv_dt.encode('ascii'), \\\n op_type.encode('ascii'), nan_is_null)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame(is_series=is_series)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n #sorting columns as per pandas result\n ret.__set_col_order([names[0]] + sorted(names[1:]))\n return ret\n\n @check_association\n def abs(self):\n \"\"\" \n returns resultant dataframe after performing \n absolute value of each column\n \"\"\"\n if not self.has_index():\n raise TypeError(\"abs: input dataframe must have index column!\")\n\n if DTYPE.STRING in self.get_types(): \n raise TypeError(\"bad operand type for abs(): 'str'\")\n \n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_abs(host, port, self.get())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame(is_series=self.is_series)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n # treatment of bool columns\n for i in range(0, len(names)):\n if self.__dict__[names[i]].dtype == DTYPE.BOOL:\n types[i] = DTYPE.BOOL\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.num_row = dummy_df[\"nrow\"]\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n\n def add(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self + other \"\"\"\n return self.__binary_operator_impl(other, \"add\", axis, level, \\\n fill_value, is_rev=False)\n\n def radd(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other + self\"\"\"\n return self.__binary_operator_impl(other, \"add\", axis, level, \\\n fill_value, is_rev=True)\n\n def __add__(self, other):\n \"\"\" \n overloaded binary operator+ (wrapper of self.add())\n returns resultant dataframe after adding self + other \n \"\"\"\n return self.add(other)\n\n def __IADD__(self, other):\n \"\"\" \n overloaded binary operator+= to perform self += other \n \"\"\"\n self = self.add(other)\n\n def sub(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self - other \"\"\"\n return self.__binary_operator_impl(other, \"sub\", axis, level, \\\n fill_value, is_rev=False)\n\n def rsub(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other - self\"\"\"\n return self.__binary_operator_impl(other, \"sub\", axis, level, \\\n fill_value, is_rev=True)\n\n def __sub__(self, other):\n \"\"\" \n overloaded binary operator- (wrapper of self.sub())\n returns resultant dataframe after adding self - other \n \"\"\"\n return self.sub(other)\n\n def __ISUB__(self, other):\n \"\"\" \n overloaded binary operator-= to perform self -= other \n \"\"\"\n self = self.sub(other)\n\n def mul(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self * other \"\"\"\n return self.__binary_operator_impl(other, \"mul\", axis, level, \\\n fill_value, is_rev=False)\n\n def rmul(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other * self\"\"\"\n return self.__binary_operator_impl(other, \"mul\", axis, level, \\\n fill_value, is_rev=True)\n\n def __mul__(self, other):\n \"\"\" \n overloaded binary operator* (wrapper of self.mul())\n returns resultant dataframe after adding self * other \n \"\"\"\n return self.mul(other)\n\n def __IMUL__(self, other):\n \"\"\" \n overloaded binary operator*= to perform self *= other \n \"\"\"\n self = self.mul(other)\n\n def truediv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self / other \"\"\"\n return self.__binary_operator_impl(other, \"fdiv\", axis, level, \\\n fill_value, is_rev=False)\n\n def rtruediv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other / self\"\"\"\n return self.__binary_operator_impl(other, \"fdiv\", axis, level, \\\n fill_value, is_rev=True)\n\n def div(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self / other \"\"\"\n return self.truediv(other, axis, level, fill_value)\n\n def rdiv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self / other \"\"\"\n return self.rtruediv(other, axis, level, fill_value)\n\n def __div__(self, other):\n \"\"\" \n overloaded binary operator/ for python 2.x (wrapper of self.truediv())\n returns resultant dataframe after adding self / other \n \"\"\"\n return self.truediv(other)\n\n def __truediv__(self, other):\n \"\"\" \n overloaded binary operator/ (wrapper of self.truediv())\n returns resultant dataframe after adding self / other \n \"\"\"\n return self.truediv(other)\n\n def __IDIV__(self, other):\n \"\"\" \n overloaded binary operator/= to perform self /= other \n \"\"\"\n self = self.truediv(other)\n\n def floordiv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self // other \"\"\"\n return self.__binary_operator_impl(other, \"idiv\", axis, level, \\\n fill_value, is_rev=False)\n\n def rfloordiv(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other // self\"\"\"\n return self.__binary_operator_impl(other, \"idiv\", axis, level, \\\n fill_value, is_rev=True)\n\n def __floordiv__(self, other):\n \"\"\" \n overloaded binary operator// (wrapper of self.floordiv())\n returns resultant dataframe after adding self // other \n \"\"\"\n return self.floordiv(other)\n\n def __IFLOORDIV__(self, other):\n \"\"\" \n overloaded binary operator//= to perform self //= other \n \"\"\"\n self = self.floordiv(other)\n\n def mod(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self % other \"\"\"\n return self.__binary_operator_impl(other, \"mod\", axis, level, \\\n fill_value, is_rev=False)\n\n def rmod(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other % self\"\"\"\n return self.__binary_operator_impl(other, \"mod\", axis, level, \\\n fill_value, is_rev=True)\n\n def __mod__(self, other):\n \"\"\" \n overloaded binary operator% (wrapper of self.mod())\n returns resultant dataframe after adding self % other \n \"\"\"\n return self.mod(other)\n\n def __IMOD__(self, other):\n \"\"\" \n overloaded binary operator%= to perform self %= other \n \"\"\"\n self = self.mod(other)\n\n def pow(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing self ** other \"\"\"\n return self.__binary_operator_impl(other, \"pow\", axis, level, \\\n fill_value, is_rev=False)\n\n def rpow(self, other, axis='columns', level=None, fill_value=None):\n \"\"\" returns resultant dataframe after performing other ** self\"\"\"\n return self.__binary_operator_impl(other, \"pow\", axis, level, \\\n fill_value, is_rev=True)\n\n def __pow__(self, other):\n \"\"\" \n overloaded binary operator** (wrapper of self.pow())\n returns resultant dataframe after adding self ** other \n \"\"\"\n return self.pow(other)\n\n def __IPOW__(self, other):\n \"\"\" \n overloaded binary operator**= to perform self **= other \n \"\"\"\n self = self.pow(other)\n\n @check_association\n def head(self, n=5):\n \"\"\"\n return first n rows of the dataframe\n \"\"\"\n if not isinstance(n, int):\n raise TypeError(\"head: Invalid type '%s' for n\"\n \"is provided!\" % (type(n).__name__))\n if n < 0:\n nrows = len(self)\n n = max(0, nrows + n)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_head(host, port, self.get(), n)\n\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n ret = DataFrame()\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n @check_association\n def tail(self, n=5):\n \"\"\"\n return last n rows of the dataframe\n \"\"\"\n if not isinstance(n, int):\n raise TypeError(\"tail: Invalid type '%s' for n\"\n \"is provided!\" % (type(n).__name__))\n if n < 0:\n nrows = len(self)\n n = max(0, nrows + n)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_tail(host, port, self.get(), n)\n\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n\n ret = DataFrame()\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n @check_association\n def __filter_slice_range(self, target):\n \"\"\"\n return filtered dataframe in given slice range\n \"\"\"\n a, b, c = target.start, target.stop, target.step\n\n if c is None:\n c = 1\n elif not isinstance(c, int):\n raise TypeError(\"filter_slice_range: slice step must be integer or None!\")\n\n if c == 0:\n raise ValueError(\"filter_slice_range: slice step cannot be zero!\")\n elif c < 0:\n raise ValueError(\"filter_slice_range: slice step cannot be negative!\")\n\n nrows = len(self)\n a_int = -1\n b_int = -1\n\n ## check for bool moved to first\n ## since isinstance(True, int) also returns True\n\n if isinstance(a, bool) or isinstance(b, bool) \\\n or not (isinstance(a, int) or a is None) \\\n or not (isinstance(b, int) or b is None):\n # non - integer slice\n if a is None:\n a_int = 0\n else:\n aloc = self.__get_index_loc_impl(a)\n if len(aloc) != 1:\n raise ValueError(\"Cannot get slice bound for \" \\\n \"non-unique label '%s'\" % (a))\n a_int = int(aloc[0])\n\n if b is None:\n b_int = nrows\n else:\n bloc = self.__get_index_loc_impl(b)\n if len(bloc) != 1:\n raise ValueError(\"Cannot get slice bound for \" \\\n \"non-unique label '%s'\" % (b))\n b_int = int(bloc[0])\n b_int += 1\n else:\n # integer slice\n a_int = int(a) if a is not None else 0\n b_int = int(b) if b is not None else nrows\n\n if a_int < 0:\n a_int = max(0, nrows + a_int)\n if b_int < 0:\n b_int = max(0, nrows + b_int)\n\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_slice_range(host, port, self.get(), a_int, b_int, c)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n ret = DataFrame()\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n if self.has_index():\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n else:\n ret.load_dummy(dummy_df[\"dfptr\"], names, types)\n return ret\n\n @check_association\n def __get_index_loc_impl(self, value):\n \"\"\"\n helper for get_index_loc\n \"\"\"\n if not self.has_index():\n raise ValueError(\"get_index_loc: no index column in input df!\")\n\n index_name = self.index.name\n dtype = self.index.dtype\n\n (host, port) = FrovedisServer.getServerInstance()\n ret = rpclib.df_get_index_loc(host, port, self.get(), \\\n index_name.encode('ascii'), \\\n str(value).encode('ascii'), \\\n dtype)\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return ret\n\n # similar to pandas pd.Index.get_loc(value)\n def get_index_loc(self, value):\n \"\"\"\n returns row-ids (int, slice or maask) for given value in index column\n \"\"\"\n idx = self.__get_index_loc_impl(value)\n sz = len(idx)\n if sz == 1: # int\n ret = int(idx[0])\n else:\n is_monotonic = np.all(np.diff(idx) == 1)\n if is_monotonic: # slice\n ret = slice(idx[0], idx[sz - 1] + 1, None)\n else: # masked-array\n mask = np.asarray([False] * len(self))\n mask[idx] = True\n ret = mask \n return ret\n\n @check_association\n def mean(self, axis=None, skipna=None, level=None, \n numeric_only=None, **kwargs):\n \"\"\"\n returns the mean of the values over the requested axis.\n \"\"\"\n axis_, skipna_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_mean(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def var(self, axis=None, skipna=None, level=None, ddof=1,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the variance of the values over the requested axis.\n \"\"\"\n axis_, skipna_, ddof_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level, ddof_=ddof)\n\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_var(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, ddof_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def std(self, axis=None, skipna=None, level=None, ddof=1,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the standard deviatioon of the values over the requested axis.\n \"\"\"\n axis_, skipna_, ddof_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level, ddof_=ddof)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_std(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, ddof_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def sem(self, axis=None, skipna=None, level=None, ddof=1,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the standard error of mean of the values over the requested axis.\n \"\"\"\n axis_, skipna_, ddof_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level, ddof_=ddof)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_sem(host, port, self.get(), \\\n cols_arr, ncol, \\\n axis_, skipna_, ddof_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n \n @check_association\n def median(self, axis=None, skipna=None, level=None,\n numeric_only=None, **kwargs):\n \"\"\"\n returns the median of the values over the requested axis.\n \"\"\"\n axis_, skipna_ = check_stat_error(axis_=axis, skipna_=skipna, \\\n level_=level)\n cols, types = self.__get_numeric_columns()\n\n ncol = len(cols)\n cols_arr = get_string_array_pointer(cols)\n type_arr = np.asarray(types, dtype=c_short)\n tptr = type_arr.ctypes.data_as(POINTER(c_short))\n (host, port) = FrovedisServer.getServerInstance()\n dummy_df = rpclib.df_median(host, port, self.get(), \\\n cols_arr, tptr, ncol, \\\n axis_, skipna_, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n # returns a series\n ret = DataFrame(is_series=True)\n names = dummy_df[\"names\"]\n types = dummy_df[\"types\"]\n ret.num_row = dummy_df[\"nrow\"]\n ret.index = FrovedisColumn(names[0], types[0]) #setting index\n ret.load_dummy(dummy_df[\"dfptr\"], names[1:], types[1:])\n return ret\n\n def __setattr__(self, key, value):\n \"\"\" sets the specified attribute \"\"\"\n if key in self.__dict__: # instance attribute\n if self.__cols and key in self.__cols:\n self[key] = value\n else:\n self.__dict__[key] = value\n else:\n attr = getattr(self.__class__, key, None)\n if isinstance(attr, property):\n if attr.fset is None:\n raise AttributeError(\"%s: can't set attribute\" % (key))\n attr.fset(self, value) # calling setter of property\n else:\n self.__dict__[key] = value\n\n @check_association\n def __str__(self):\n \"\"\"\n returns string representation of the dataframe \n \"\"\"\n (host, port) = FrovedisServer.getServerInstance()\n df_str = rpclib.df_to_string(host, port, self.__fdata, self.has_index())\n excpt = rpclib.check_server_exception()\n if excpt[\"status\"]:\n raise RuntimeError(excpt[\"info\"])\n return df_str\n\n def __repr__(self):\n \"\"\"\n returns string representation of the dataframe \n \"\"\"\n return self.__str__()\n\nFrovedisDataframe = DataFrame\n","sub_path":"src/foreign_if/python/main/python/frovedis/dataframe/df.py","file_name":"df.py","file_ext":"py","file_size_in_byte":130151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"618279786","text":"import torch\nfrom torch.utils.data import DataLoader\nimport argparse\n\ndef main(args):\n\n # cuda\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n # Datasets & Dataloader\n train_set = torch.utils.data.Dataset()\n train_loader = DataLoader(dataset=train_set, shuffle=True, batch_size=args.batch_size)\n\n valid_set = torch.utils.data.Dataset()\n valid_loader = DataLoader(dataset=valid_set, batch_size=args.batch_size)\n\n # Models\n model = torch.nn.Module()\n model.to(device)\n\n # Optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)\n\n # Training\n best_valid_loss = 1e99\n for epoch in range(1, args.epochs+1):\n \n train_loss = evaluate_epoch(model=model, data_loader=train_loader, optimizer=optimizer)\n valid_loss = evaluate_epoch(model=model, data_loader=valid_loader)\n\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n best_epoch = epoch\n model.save()\n \n print(\"Epoch %02d/%02d Train Loss %5.3f Valid Loss %5.3f\"\n %(epoch, args.epochs, train_loss, valid_loss))\n\n raise NotImplementedError()\n\ndef evaluate_epoch(model, data_loader, optimizer=None):\n \n epoch_loss = 0\n\n if optimizer is not None:\n torch.enable_grad()\n model.train()\n else:\n torch.no_grad()\n model.eval()\n \n for batch in data_loader:\n\n loss = model(batch)\n\n if optimizer is not None:\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n epoch_loss += loss.item()\n\n return epoch_loss/len(data_loader)\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-ep', '--epochs', type=int)\n parser.add_argument('-bs', '--batch_size', type=int)\n parser.add_argument('-lr', '--learning_rate', type=float)\n\n # parser.add_argument('-bool', '--boolean', action=store_true)\n\n args = parser.parse_args()\n \n main(args)","sub_path":"base/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"511452080","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 5 13:27:15 2021\r\n\r\n@author: Hitesh\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nfrom db_conn import hana_conn\r\n#from datetime import date\r\n\r\n# st_date = date.today()\r\n# ed_date = date.today()\r\n \r\nclass operations:\r\n \r\n def __init__(self, CUST_ID, FIRST_NAME, LAST_NAME, REGION, ID_PROOF_TYPE, START_DATE, END_DATE, STATUS):\r\n self.CUST_ID = CUST_ID\r\n self.FIRST_NAME = FIRST_NAME\r\n self.LAST_NAME = LAST_NAME\r\n self.REGION = REGION\r\n self.ID_PROOF_TYPE = ID_PROOF_TYPE\r\n self.START_DATE = 'current_date'\r\n self.END_DATE = 'current_date'\r\n self.STATUS = STATUS\r\n self.conn=hana_conn() \r\n \r\n \r\n def read(self):\r\n cursor = self.conn.cursor() \r\n #cursor.execute(\"SELECT TOP 10 \"CUST_ID\",\"FIRST_NAME\",\"LAST_NAME\",\"REGION\",\"ID_PROOF_TYPE\",\"START_DATE\",\"END_DATE\",\"STATUS\" FROM CUSTOMER_DATA;\", {}) \r\n cursor.execute(\"SELECT TOP 10 * FROM CUSTOMER;\", {}) \r\n data = cursor.fetchall()\r\n print(\"Connection to SAP HANA Service successful.\")\r\n \r\n df = pd.DataFrame(data, columns=['CUST_ID','FIRST_NAME','LAST_NAME','REGION','ID_PROOF_TYPE','START_DATE','END_DATE','STATUS'])\r\n print(df)\r\n return df\r\n\t\r\n \r\n def create(self):\r\n #if variable=='Read'\r\n \r\n #cursor = self.conn.cursor() \r\n # val = (self.CUST_ID,self.FIRST_NAME,self.LAST_NAME,self.REGION,self.ID_PROOF_TYPE,self.START_DATE,self.END_DATE,self.STATUS)\r\n # sql=\"INSERT INTO CUSTOMER (CUST_ID,FIRST_NAME,LAST_NAME,REGION,ID_PROOF_TYPE,START_DATE,END_DATE,STATUS) VALUES\"\r\n # final_sql= (sql, val) \r\n # print(final_sql)\r\n # cursor.execute(final_sql, {})\r\n cursor = self.conn.cursor() \r\n cursor.execute(\"INSERT INTO CUSTOMER (CUST_ID,FIRST_NAME,LAST_NAME,REGION,ID_PROOF_TYPE,START_DATE,END_DATE,STATUS) VALUES('12345', 'Sidney', 'Hauke', 'New Jersey', 'Driving License', 'current_date', 'current_date', 'Active')\", {}) \r\n print(\"Customer got created\" )\r\n \r\n return \"Customer created\"\r\n \r\n def delete(self): \r\n cursor = self.conn.cursor() \r\n cursor.execute(\"DELETE FROM CUSTOMER WHERE CUST_ID =\"+str(self.CUST_ID), {})\r\n # res=cursor.fetchall() \r\n # print(res)\r\n print(\"Customer got removed\" )\r\n #return res\r\n return \"Customer got removed\" \r\n \r\n cursor.close()\r\n hana_conn.close() \r\n\r\n\r\n#unit testing \r\n# test = operations('12345','Sidney','Hauke','New Jersey','Driving License','s','e','Active')\r\n# test.delete()\r\n","sub_path":"customerapp.py","file_name":"customerapp.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"271255006","text":"import endpoints\nfrom protorpc import messages\nfrom protorpc import message_types\nfrom protorpc import remote\n\n#import datetime\nfrom google.appengine.ext import ndb\n\n\nclass GardenData(ndb.Model):\n date = ndb.DateTimeProperty(auto_now_add=True)\n soil_temp = ndb.FloatProperty()\n soil_moist = ndb.IntegerProperty()\n room_temp = ndb.IntegerProperty()\n room_moist = ndb.IntegerProperty()\n \n @classmethod\n def query_data(cls):\n qry = cls.query().order(-cls.date)\n return qry.fetch(1000)\n \n \npackage = 'gardendatapackage'\n\n@endpoints.api(name='gardendata', version='v1')\nclass GardenDataApi(remote.Service):\n \"\"\"Garden Data API v1.\"\"\"\n \n CONTAINER = endpoints.ResourceContainer(\n soil_temp = messages.FloatField(1, variant=messages.Variant.FLOAT, \n required=True),\n soil_moist = messages.IntegerField(2, variant=messages.Variant.UINT32,\n required=True),\n room_temp = messages.IntegerField(3, variant=messages.Variant.INT32,\n required=True),\n room_moist = messages.IntegerField(4, variant=messages.Variant.UINT32,\n required=True) \n )\n \n @endpoints.method(CONTAINER,\n path='api', http_method='POST',\n name='data.post')\n def save_data(self, request):\n gd = GardenData(soil_temp = request.soil_temp, \n soil_moist = request.soil_moist,\n room_temp = request.room_temp,\n room_moist = request.room_moist)\n \n gd.put()\n \n return message_types.VoidMessage() \n \n\nAPPLICATION = endpoints.api_server([GardenDataApi])","sub_path":"Google App Engine/garden_data_api.py","file_name":"garden_data_api.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"196337068","text":"import time,os,operator\n\ndef string_amend(str):\n strAmend = str.replace('\"', '')\n strAmend2 = strAmend.replace(',','')\n strAmend3 = strAmend2.replace(' ','')\n strAmend4 = strAmend3.replace('\\n','')\n return strAmend4\n\ndef bucketRtrv(c):\n new = c.split('\"bucket\":') #splits string on bucket: so that data before bucket name is moved to [0] and bucket name is moved to [1]\n del(new[0]) #deletes data before the actual bucket name that is stored in [0]\n str1 = ''.join(new) #turns the list into string for increased manipulation\n str2 = str1.split('\"pool\":') #splits the new string after the bucket name, on pool:, so that bucket name is now held in [0] and unneeded data in [1]\n if (len(str2)<2): #however, if the list is shorter than 2 elements, then there is no bucket name. Output bucket name as 'none'\n final = (\"None\")\n return final\n else:\n del(str2[1]) #If there is a bucket name, it is stored in [0], so [1] is deleted\n str3 = ''.join(str2) #Turn the bucket name back into string for manipulation\n return (string_amend(str3))\ndef idRtrv(c):\n new = c.split('\"id\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"marker\":')\n if (len(str2)<2):\n final = (\"None\")\n return final\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef ownerRtrv(c):\n new = c.split('\"owner\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"ver\":')\n if (len(str2)<2):\n final = (\"None\")\n return final\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef size_kbRtrv(c):\n new = c.split('\"size_kb\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"size_kb_actual\":')\n if (len(str2)<2):\n final=\"0\"\n return final \n else:\n if (len(str2)>4):\n del(str2[4])\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3)) \n elif (len(str2)>3):\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\n elif (len(str2)>2):\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return(string_amend(str3))\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef size_kb_actualRtrv(c):\n new = c.split('\"size_kb_actual\":')\n del(new[0])\n str1 = ''.join(new)\n str2 = str1.split('\"num_objects\":')\n if (len(str2)<2):\n final=\"0\"\n return final \n else:\n if (len(str2)>4):\n del(str2[4])\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3)) \n elif (len(str2)>3):\n del(str2[3])\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3)) \n elif (len(str2)>2):\n del(str2[2])\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\n else:\n del(str2[1])\n str3 = ''.join(str2)\n return (string_amend(str3))\ndef num_objectsRtrv(c):\n new = c.split('\"num_objects\":')\n if (len(new)>4):\n del(new[4])\n del(new[3])\n del(new[2])\n del(new[0])\n str1 = ''.join(new)\n return (string_amend(str1))\n elif (len(new)>3):\n del(new[3])\n del(new[2])\n del(new[0])\n str1 = ''.join(new)\n return(string_amend(str1))\n elif (len(new)>2):\n del(new[2])\n del(new[0])\n str1 = ''.join(new)\n return (string_amend(str1))\n del(new[0])\n str1 = ''.join(new)\n str1Amend = str1.replace('}', '')\n str1Amend2 = str1Amend.replace(',','')\n str1Amend3 = str1Amend2.replace(' ','')\n str1Amend4 = str1Amend3.replace('\\n','')\n if (str1Amend4==\"\"):\n final=\"0\"\n #print(final) use for fault checking\n return final\n else:\n str1Amend3 =str1Amend2.replace(']','')\n str1Amend4 = str1Amend3.replace(' ','')\n str1Amend5 = str1Amend4.replace('\\n','')\n return str1Amend5\n\nf=open('serverOutput.txt','r+') ##f=open('/usr/bin/radosgw-admin bucket stats','r+') Execute straight from this directory\nx=f.read()\ny=x.split('},'or']')\nz=[]\n \nfor c in y:\n n=bucketRtrv(c),idRtrv(c),ownerRtrv(c),size_kbRtrv(c),size_kb_actualRtrv(c),num_objectsRtrv(c)\n z.append(n)\n\n\n\nrotated = zip(*z[::1])\nrotated3 = rotated[2]\nrotated.remove(rotated3)\nrotated.insert(0,rotated3)\n\n\n\nfor i,c in enumerate(rotated):\n new=[]\n for x in c:\n new.append(x)\n rotated[i] = new\n\nfor i,c in enumerate(rotated[0]):\n if c=='None':\n rotated[0][i] = rotated[0][i-1]\n\nspaceUsed_kb= {}\nspaceUsed_kb_actual = {}\nfor i,c in enumerate(rotated[0]):\n if c not in spaceUsed_kb:\n spaceUsed_kb[c] = int(rotated[3][i])\n if c in spaceUsed_kb:\n spaceUsed_kb[c] = int(spaceUsed_kb[c])+int(rotated[3][i])\nfor i,c in enumerate(rotated[0]):\n if c not in spaceUsed_kb_actual:\n spaceUsed_kb_actual[c] = int(rotated[4][i])\n if c in spaceUsed_kb_actual:\n spaceUsed_kb_actual[c] = int(spaceUsed_kb_actual[c])+int(rotated[4][i])\n\n\n##function for sorting lists##\ndef sort_inner(inner):\n return inner[0]\n\nz = zip(*rotated[::1])\nz.sort(key=sort_inner)\n\ntemp =[]\ndictlist =[]\nfor key, value in spaceUsed_kb.iteritems():\n value=float(value)\n value = \"%.3f\" % float(value/(1048576))\n value = str(value)+'gb'\n temp = key,value\n dictlist.append(temp)\n\n\n\nlistOfTemps = []\nfor c in dictlist[::1]:\n dictlist.remove(c)\n temp2 = str(c).replace(\"'\",'').replace(',',' has used').replace('(','').replace(')','')\n listOfTemps.append(temp2)\ndictlist = dictlist + listOfTemps\n\n##Transferring dictionary into list which is stored in dictlist2##\ndictlist2 =[]\nfor key, value in spaceUsed_kb_actual.iteritems():\n value=float(value)\n value = \"%.3f\" % float(value/(1048576))\n value = str(value)+'gb'\n temp2 = key,value\n dictlist2.append(temp2)\n\n\ntemp3 =[]\nlistOfTemps2=[]\nfor c in dictlist2[::1]:\n dictlist2.remove(c)\n temp3 = str(c).replace(\"'\",'').replace(',',' has used').replace('(','').replace(')','')\n listOfTemps2.append(temp3)\ndictlist2 = dictlist2 + listOfTemps2\n\n##sort the totals in alphabetical order of owner##\ndictlist.sort(key=sort_inner)\ndictlist2.sort(key=sort_inner)\n\n\n##convert both lists to strings for writing to file##\ndictlistStr=str(dictlist)\ndictlist2Str=str(dictlist2)\n\n\n\n##Concatenates headings in 'startZ' with data in 'z'##\n\n\nfileOutput = 'Server Outputs'+'/'+(\"diskSpace\" + (time.strftime(\"%d.%m.%Y\") +\".csv\")) #creates dir called Server Outputs and file called diskSpace(date)\n\ndir = os.path.dirname(fileOutput)\n\nif not os.path.exists(dir):\n os.makedirs(dir)\n\n\ndictlist = tuple(dictlist)\ndictlist = [dictlist]\n#print(dictlist[0][1])\n#print(z[1])\nzNew=[]\nfor c in z: #Added column which shows data used by each person, however, it duplicates info\n for d in dictlist[0]:\n if d.find(c[0])!=-1:\n d=(d,)\n print(d)\n c=c+d\n print(c)\n zNew.append(c)\n\n\nf2=open(fileOutput, 'w+')\nf2.write(\"\\n\".join(map(lambda x: str(x).replace('(','').replace(')','').replace(\"'\",''), zNew)))\nf2.write('\\n\\n')\n#f2.write('\\n'+'size_kb, '+(dictlistStr.replace('[','').replace(']','').replace(\"'\",'')))\n#f2.write('\\n'+'size_kb_actual, '+(dictlist2Str.replace('[','').replace(']','').replace(\"'\",'')))\nf2.close()\nf.close()\n","sub_path":"src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":7876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"388372830","text":"\"\"\"\nThis code has been taken from\nhttps://blog.hypertrack.io/2016/10/08/dealing-with-database-transactions-in-django-celery/\n\nUsage:\n from pretix.base.services.async import TransactionAwareTask\n @task(base=TransactionAwareTask)\n def task_…():\n\"\"\"\nimport cProfile\nimport os\nimport random\nimport time\n\nfrom django.conf import settings\nfrom django.db import transaction\n\nfrom pretix.celery_app import app\n\n\nclass ProfiledTask(app.Task):\n\n def __call__(self, *args, **kwargs):\n\n if settings.PROFILING_RATE > 0 and random.random() < settings.PROFILING_RATE / 100:\n profiler = cProfile.Profile()\n profiler.enable()\n starttime = time.time()\n ret = super().__call__(*args, **kwargs)\n profiler.disable()\n tottime = time.time() - starttime\n profiler.dump_stats(os.path.join(settings.PROFILE_DIR, '{time:.0f}_{tottime:.3f}_celery_{t}.pstat'.format(\n t=self.name, tottime=tottime, time=time.time()\n )))\n return ret\n else:\n return super().__call__(*args, **kwargs)\n\n\nclass TransactionAwareTask(ProfiledTask):\n \"\"\"\n Task class which is aware of django db transactions and only executes tasks\n after transaction has been committed\n \"\"\"\n\n def apply_async(self, *args, **kwargs):\n \"\"\"\n Unlike the default task in celery, this task does not return an async\n result\n \"\"\"\n transaction.on_commit(\n lambda: super(TransactionAwareTask, self).apply_async(*args, **kwargs)\n )\n","sub_path":"src/pretix/base/services/async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"221783484","text":"import sys\n\nsys.path.insert(0, \"./yolov5\")\n\nfrom yolov5.utils.datasets import LoadImages, LoadStreams\nfrom yolov5.utils.general import check_img_size, non_max_suppression, scale_coords\nfrom yolov5.utils.torch_utils import select_device, time_synchronized\nfrom helpers.parser import get_config\nfrom deep_sort_pytorch.deep_sort import DeepSort\nfrom iou.iou_tracker import IOUTracker\n# from iou_kf.iou_kf_tracker import IOUKFTracker\nfrom sort.sort import Sort\nimport argparse\nimport os\nimport platform\nimport shutil\nimport time\nfrom pathlib import Path\nimport cv2\nimport torch\nimport torch.backends.cudnn as cudnn\nimport constants\nimport csv\nimport numpy as np\n\n\npalette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1)\n\n\ndef xyxy_to_tlwh(bbox_xyxy):\n tlwh_bboxs = []\n for box in bbox_xyxy:\n x1, y1, x2, y2 = [int(i) for i in box]\n top = y1\n left = x1\n w = int(x2 - x1)\n h = int(y2 - y1)\n tlwh_obj = [left, top, w, h]\n tlwh_bboxs.append(tlwh_obj)\n return tlwh_bboxs\n\n\ndef bbox_rel(*tlwh):\n \"\"\" Calculates the relative bounding box from absolute pixel values.\"\"\"\n bbox_left, bbox_top, bbox_w, bbox_h = tlwh\n x_c = bbox_left + bbox_w / 2\n y_c = bbox_top + bbox_h / 2\n w = bbox_w\n h = bbox_h\n return x_c, y_c, w, h\n\n\ndef compute_color_for_labels(label):\n \"\"\"\n Simple function that adds fixed color depending on the class\n \"\"\"\n color = [int((p * (label ** 2 - label + 1)) % 255) for p in palette]\n return tuple(color)\n\n\ndef draw_boxes(img, bbox, identities=None, offset=(0, 0)):\n for i, box in enumerate(bbox):\n x1, y1, x2, y2 = [int(i) for i in box]\n x1 += offset[0]\n x2 += offset[0]\n y1 += offset[1]\n y2 += offset[1]\n # box text and bar\n id = int(identities[i]) if identities is not None else 0\n color = compute_color_for_labels(id)\n label = \"{}{:d}\".format(\"\", id)\n t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]\n cv2.rectangle(img, (x1, y1), (x2, y2), color, 3)\n cv2.rectangle(\n img, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4), color, -1\n )\n cv2.putText(\n img,\n label,\n (x1, y1 + t_size[1] + 4),\n cv2.FONT_HERSHEY_PLAIN,\n 2,\n [255, 255, 255],\n 2,\n )\n return img\n\n\ndef detect(cfg, save_img=False):\n out, source, view_img, save_txt, imgsz, gt_file = (\n cfg.OUTPUT,\n cfg.SOURCE,\n cfg.VIEW_IMG,\n cfg.SAVE_TXT,\n cfg.IMAGE_SIZE,\n cfg.GT_FILE\n )\n\n # Initialize\n device = select_device(cfg.DEVICE)\n\n # Create output folder\n exp_name = \"exp_\" + cfg.EXP_ID\n out = os.path.join(out, exp_name)\n if os.path.exists(out):\n shutil.rmtree(out) # delete output folder\n os.makedirs(out) # make new output folder\n\n half = device.type != \"cpu\" # half precision only supported on CUDA\n\n # Read groundtruth\n gt = np.genfromtxt(gt_file, delimiter=',')\n\n # Set Dataloader\n vid_path, vid_writer = None, None\n view_img = True\n save_img = True\n dataset = LoadImages(source, img_size=imgsz)\n\n t0 = time.time()\n\n save_path = str(Path(out))\n txt_path = str(Path(out)) + \"/results.txt\"\n\n seen_vid_paths = {}\n\n for frame_idx, (path, img, im0s, vid_cap) in enumerate(dataset):\n if path not in seen_vid_paths:\n seen_vid_paths[path] = True\n if cfg.TRACKER == constants.DEEP_SORT:\n # initialize deepsort\n tracker = DeepSort(\n cfg.DEEP_SORT.REID_CKPT,\n max_dist=cfg.DEEP_SORT.MAX_DIST,\n min_confidence=cfg.DEEP_SORT.MIN_CONFIDENCE,\n nms_max_overlap=cfg.DEEP_SORT.NMS_MAX_OVERLAP,\n max_iou_distance=cfg.DEEP_SORT.MAX_IOU_DISTANCE,\n max_age=cfg.DEEP_SORT.MAX_AGE,\n n_init=cfg.DEEP_SORT.N_INIT,\n nn_budget=cfg.DEEP_SORT.NN_BUDGET,\n use_cuda=True,\n )\n elif cfg.TRACKER == constants.IOU:\n sigma_iou = 1 - cfg.IOU.MAX_IOU_DISTANCE\n # initialize iou\n tracker = IOUTracker(\n sigma_l=cfg.IOU.MIN_CONFIDENCE,\n sigma_iou=sigma_iou,\n )\n elif cfg.TRACKER == constants.SORT:\n # initialize sort\n tracker = Sort(\n min_confidence=cfg.SORT.MIN_CONFIDENCE,\n max_iou_distance=cfg.SORT.MAX_IOU_DISTANCE,\n max_age=cfg.SORT.MAX_AGE,\n n_init=cfg.SORT.N_INIT,\n )\n\n frame_col_idx = 0\n frame_n = frame_idx + 1\n pred = gt[gt[:, frame_col_idx] == frame_n] \n\n bbox_xywh = []\n confs = []\n\n p, s, im0 = path, \"\", im0s\n s += \"%gx%g \" % img.shape[1:] # print string\n save_path = str(Path(out) / Path(p).name)\n\n # Process detections\n if pred is not None and len(pred):\n for frame, id, *tlwh, conf, cls, visibility in pred:\n if int(cls) == 1:\n x_c, y_c, bbox_w, bbox_h = bbox_rel(*tlwh)\n obj = [x_c, y_c, bbox_w, bbox_h]\n bbox_xywh.append(obj)\n confs.append(conf)\n\n xywhs = torch.Tensor(bbox_xywh)\n confss = torch.Tensor(confs)\n\n # Pass detections to iou/sort/deepsort tracker\n outputs = tracker.update(xywhs, confss, im0)\n\n # draw boxes for visualization\n if len(outputs) > 0:\n bbox_xyxy = outputs[:, :4]\n identities = outputs[:, -1]\n draw_boxes(im0, bbox_xyxy, identities)\n # to MOT format\n tlwh_bboxs = xyxy_to_tlwh(bbox_xyxy)\n\n # Write MOT compliant results to file\n if save_txt:\n fieldnames = [\n \"frame\",\n \"id\",\n \"bb_left\",\n \"bb_top\",\n \"bb_width\",\n \"bb_height\",\n \"conf\",\n \"x\",\n \"y\",\n \"z\",\n ]\n\n for j, (tlwh_bbox, output) in enumerate(zip(tlwh_bboxs, outputs)):\n bbox_left = tlwh_bbox[0]\n bbox_top = tlwh_bbox[1]\n bbox_w = tlwh_bbox[2]\n bbox_h = tlwh_bbox[3]\n identity = output[-1]\n with open(txt_path, 'a') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writerow({\n \"frame\": frame_n,\n \"id\": identity,\n \"bb_left\": float(bbox_left),\n \"bb_top\": float(bbox_top),\n \"bb_width\": float(bbox_w),\n \"bb_height\": float(bbox_h),\n \"conf\": -1,\n \"x\": -1,\n \"y\": -1,\n \"z\": -1,\n })\n else:\n tracker.increment_ages()\n\n # Print time (inference + NMS)\n # print(\"%sDone. (%.3fs)\" % (s, t2 - t1))\n\n # Stream results\n view_img = cfg.VIEW_IMG\n if view_img:\n cv2.imshow(p, im0)\n if cv2.waitKey(1) == ord(\"q\"): # q to quit\n raise StopIteration\n\n # Save results (image with detections)\n if save_img:\n print(\"saving img!\")\n if dataset.mode == \"images\":\n cv2.imwrite(save_path, im0)\n else:\n print(\"saving video!\")\n if vid_path != save_path: # new video\n vid_path = save_path\n if isinstance(vid_writer, cv2.VideoWriter):\n vid_writer.release() # release previous video writer\n\n # fps = vid_cap.get(cv2.CAP_PROP_FPS)\n fps = cfg.FPS\n w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n vid_writer = cv2.VideoWriter(\n save_path,\n cv2.VideoWriter_fourcc(*cfg.FOURCC),\n fps,\n (w, h),\n )\n vid_writer.write(im0)\n\n if save_txt or save_img:\n print(\"Results saved to %s\" % os.getcwd() + os.sep + out)\n if platform == \"darwin\": # MacOS\n os.system(\"open \" + save_path)\n\n print(\"Done. (%.3fs)\" % (time.time() - t0))\n\n\ndef main(config):\n cfg = get_config(config)\n cfg.IMAGE_SIZE = check_img_size(cfg.IMAGE_SIZE)\n print(cfg)\n\n with torch.no_grad():\n detect(cfg)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config\", type=Path, required=True)\n args = parser.parse_args()\n main(args.config)\n","sub_path":"track_by_gt_bbox.py","file_name":"track_by_gt_bbox.py","file_ext":"py","file_size_in_byte":9295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"207244791","text":"class Solution:\n def reverseWords(self, s):\n if s == '':\n return s\n ls = s.split()\n if ls == []:\n return ''\n\n res = ''\n for i in range(len(ls) - 1):\n res += ls[len(ls) - 1 - i] + ' '\n res += ls[0]\n return res\n","sub_path":"151_ReverseWordsInAString.py","file_name":"151_ReverseWordsInAString.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"352162141","text":"from fiasko_bro import validators\nfrom fiasko_bro.code_validator import CodeValidator\n\n\ndef test_has_no_directories_from_blacklist(test_repo):\n expected_output = 'data_in_repo', '.vscode'\n blacklists = CodeValidator.blacklists\n output = validators.has_no_directories_from_blacklist(\n solution_repo=test_repo,\n blacklists=blacklists,\n )\n assert output == expected_output\n\n\ndef test_no_star_imports_ok(origin_repo):\n blacklists = CodeValidator.blacklists\n output = validators.has_no_directories_from_blacklist(\n solution_repo=origin_repo,\n blacklists=blacklists,\n )\n assert output is None\n","sub_path":"tests/test_general_validators/test_has_no_directories_from_blacklist.py","file_name":"test_has_no_directories_from_blacklist.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"608855921","text":"# 대부분의 코드는 https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/15_Style_Transfer.ipynb 에서 가져옴 \n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL.Image\n\n\"\"\"이미지 조작을 위한 헬퍼 함수\"\"\"\n# 이 함수는 이미지를 로드하고 부동소수점 형식의 NumPy 배열을 반환한다.\n# 이미지는 크기가 자동으로 조정되며 높이 또는 너비 중 가장 큰 것이 max_size와 같아진다\n# 또는 지정한 크기로 조정될 수 있다.\ndef load_image(filename, shape=None, max_size=None):\n image = PIL.Image.open(filename)\n\n if max_size is not None:\n # 최대 높이와 너비를 유지하면서 적절한 비율로 조정하기 위해 적절하게 계산해야한다\n factor = float(max_size) / np.max(image.size)\n\n # 이미지의 높이와 너비 조정\n size = np.array(image.size) * factor\n\n # 크기가 조정되어서 사이즈가 부동 소수점 형식을 따르지만 PIL은 정수 입력을 요구한다.\n size = size.astype(int)\n\n # 이미지를 재조정한다\n image = image.resize(size, PIL.Image.LANCZOS) # PIL.Image.LANCZOS 는 리샘플링 필터중 하나이다.\n\n if shape is not None:\n image = image.resize(shape, PIL.Image.LANCZOS) # PIL.Image.LANCZOS 는 리샘플링 필터중 하나이다.\n\n # 부동소수점 형식의 Numpy 배열로 변환한다.\n return np.float32(image)\n\n# JPEG 형태로 이미지를 저장한다\n# 이미지는 0~255 사이로 픽셀 값이 정해진 NumPy 배열로 주어진다.\ndef save_image(image, filename):\n # 픽셀 값이 0에서 255 사이인지 확인\n image = np.clip(image, 0.0, 255.0)\n\n # bytes로 변환\n image = image.astype(np.uint8)\n\n # JPEG로 이미지 저장\n with open(filename, 'wb') as file:\n PIL.Image.fromarray(image).save(file, 'jpeg')\n\n# 콘텐츠 이미지, 혼합된 이미지 및 스타일 이미지를 그립니다.\ndef plot_images(content_image, style_image, mixed_image):\n # 서브플롯으로 이미지 생성\n fig, axes = plt.subplots(1, 3, figsize=(10, 10))\n\n # 수직 간격 조절\n fig.subplots_adjust(hspace=0.1, wspace=0.1)\n\n # 콘텐츠 이미지를 그린다\n # 픽셀 값은 값을 255로 나눔으로써 0~1 사이 영역으로 정규화 된다\n ax = axes.flat[0]\n ax.imshow(content_image / 255.0, interpolation='sinc')\n ax.set_xlabel(\"Content\")\n\n # 혼합된 이미지를 그린다.\n ax = axes.flat[1]\n ax.imshow(mixed_image / 255.0, interpolation='sinc')\n ax.set_xlabel(\"Output\")\n\n # 스타일 이미지를 그린다\n ax = axes.flat[2]\n ax.imshow(style_image / 255.0, interpolation='sinc')\n ax.set_xlabel(\"Style\")\n\n # 모든 그림에서 틱 제거\n for ax in axes.flat:\n ax.set_xticks([])\n ax.set_yticks([])\n\n # 싱글 노트북 셀에서 이미지가 여러개로 잘 표시되는지 확인하자.\n plt.show()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"394036550","text":"from django.urls import path\n\nimport apps.comments.views as comments\n\nfrom .apps import CommentsConfig\n\napp_name = CommentsConfig.name\n\nurlpatterns = [\n path(\"create/\", comments.comment_create, name=\"comment_create\"),\n path(\"create-child//\",\n comments.child_comment_create, name=\"comment_child_create\"),\n path(\"ajax/like\", comments.like_dislike_ajax, name=\"ajax_comment\"),\n]\n","sub_path":"apps/comments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"607256812","text":"#1.要想读取csv文件,首先要导入csv代码库\n#这个csv也不用下载,是python内置的代码库\n#如果要读取excel需要下载相应的代码库:xlrd\n#怎么下载:1.通过命令下载:在dos窗口中输入pip install -U xlrd\n#之前老师发了一个selenium的离线包,也可以通过命令行在线安装\n## 在dos窗口中输入pip install -U selenium或者pip3 install selenium\n#-U是升级到新版的意思 pip是python语言最常用的项目管理工具,和jav中的maven类似\n#如果又安装python2.同时安装python3,那么可能需要把pip改成pip3\n#2.点击file-点击settings-project下面的inter preter-点击+号-搜索需要的代码库,并可直接安装\nimport csv\n#指定要读取的文件的路径\npath='C:/Users/51Testing/PycharmProjects/selenium1th/data/test_data.csv'\n#因为字符串中包含转义字符\\t等,怎么做?\n#方法1:每个反斜线前面加一个反斜线\n#方法2:把每个反斜线都改成正斜线\n#相比第二种方法更好,因为java、python语言都是跨平台的,在字符串中,两个反斜线会自动根据转义字符的规则转成一个反斜线,在windows操作系统中,用反斜线表示目录结构,但是在linux操作系统中,只有正斜线/才能表示目录。如果用双反斜线,代码就失去了跨平台的能力,因为linux用不了反斜线。如果用正斜线,代码可以同时在linux和windows中执行\n#方法3.在字符串外面加上一个字母r,会认为中间的所有的代码都不存在转义\nprint(path)\n#3.打开路径所对应的文件\nfile=open(path,'r')\n#4.读取文件的内容,通过什么来读取?我们导入了csv代码库,还一直没用\n#reader()方法是专门用来读取文件的\ndata_table=csv.reader(file)\n#5.打印data_table中的每一行数据,怎么办?写一个for-each循环\n#for是循环的关键字,item代表每一行,每循环一次,item就代表最新的一行数据。data_table表示整个文件中的所有数据\nfor item in data_table:\n print(item)\n#很多的测试用例可能都需要从excel中读取数据,所以我们应该对这些代码做一个简单的封装,建一个文件叫csvFileManager2,把以上代码封装到一个方法中,并且再建一个文件来读取封装好的方法\n","sub_path":"day4/csvFileManager.py","file_name":"csvFileManager.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"468146599","text":"from PIL import Image, ImageDraw, ImageFont\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport cv2\n\n\n\ndef elastic_distortion(image, alpha, sigma, random_state=None): #Create an elastic distortion of the image to account for camera iregularities\n if random_state is None:\n random_state = np.random.RandomState(None)\n\n shape = image.shape\n dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=\"constant\", cval=0) * alpha\n dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=\"constant\", cval=0) * alpha\n dz = np.zeros_like(dx)\n\n x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]))\n indices = np.reshape(y+dy, (-1, 1)), np.reshape(x+dx, (-1, 1))\n distored_image = map_coordinates(image, indices, order=1, mode='reflect')\n return distored_image.reshape(image.shape)\n\n \ndef add_noise(img): #Add noise to the image\n row, col=np.shape(img)\n mean = 0\n var = 2\n sigma = var**0.3\n gauss = np.array((row, col))\n gauss = np.random.normal(mean,sigma,(row,col))\n gauss = gauss.reshape(row,col)\n noisy = img + gauss\n return noisy.astype('uint8')\n\ndef add_side_bars(img):\n \n for i in range(0, 4): #sides bars 4 pixel wide\n img[i, :]=np.random.randint(0, 255)\n img[-i, :]=np.random.randint(0, 255)\n img[:, i]=np.random.randint(0, 255)\n img[:, -i]=np.random.randint(0, 255)\n return img\n\ndef get_image_part(img, cell_size):\n x=np.random.randint(19, 40)\n y=np.random.randint(19, 40)\n img=img[x:x+cell_size, y:y+cell_size]\n return img\n\n\ndef create_data(length, list_of_font, threshold=True, consider_empty=True):\n cell_size=45\n y_label=np.zeros(length, dtype=int)\n \n x_img=np.zeros((length, cell_size, cell_size), dtype=float)\n for i in range(0, length):\n \n if consider_empty:\n y=np.random.randint(0, 9+1)\n \n else:\n y=np.random.randint(1, 9+1)\n \n y_label[i]=y\n \n strip_width, strip_height = 100, 100\n\n background =Image.new('RGB', (strip_width, strip_height), color = (np.random.randint(80, 255), np.random.randint(80, 255), np.random.randint(80, 255)))\n font1=list_of_font[np.random.randint(0, len(list_of_font))]\n font = ImageFont.truetype(font1, 40)\n draw = ImageDraw.Draw(background)\n text_width, text_height = draw.textsize(text, font)\n position = ((strip_width-text_width)/2,(strip_height-text_height)/2)\n color=(np.random.randint(0, 10), np.random.randint(0, 10), np.random.randint(0, 10))\n \n if y>0: #If label is greater than 0, draw number\n draw.text(position, str(y), color, font=font)\n #add bars of differents width around the cell:\n img=np.array(background)\n img=0.2989*img[:, :, 0]+0.5870*img[:, :, 1]+0.1140*img[:, :, 2]\n bar_w=np.random.randint(1, 4)\n img[:, 28:28+bar_w]=1\n bar_w=np.random.randint(1, 4)\n img[:, 74:74+bar_w]=1\n bar_w=np.random.randint(1, 4)\n img[28:28+bar_w, :]=1\n bar_w=np.random.randint(1, 4)\n img[74:74+bar_w, :]=1\n \n #Get images of different centers around the original cells center\n img=get_image_part(img, cell_size)\n \n img=add_noise(img)\n img = cv2.GaussianBlur(img, (3,3), 0)\n img=elastic_distortion(img, np.random.randint(0, 100), np.random.randint(5, 10), random_state=None)\n x_img[i, :, :]=img\n \n return x_img, y_label\n \n\ndef create_image_data(length):\n\n list_of_font=['/Library/Fonts/Arial.ttf', '/Library/Fonts/Courier New.ttf', '/Library/Fonts/Times New Roman.ttf']\n #ll=80000\n xx, yy=generate_digit_img(length, list_of_font)\n return xx, yy\n\n","sub_path":"train_digit_model/generate_digits.py","file_name":"generate_digits.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"417730442","text":"import numpy as np\r\nimport random as rnd\r\nimport operations\r\n\r\n\r\n# fe = open('fkeasypart4.lower','r')\r\n# fd = open('fkdifficpart4.lower','r')\r\n# fouts2t=open('fksrc2trg.lower','w')\r\n# foutt2s=open('fktrg2src.lower','w')\r\n# rnd.seed(7)\r\n\r\n\r\ndef repeatnoise(fe):\r\n fouts2t = []\r\n for e in fe:\r\n # create fksrc2trg\r\n easy = e.strip().split()\r\n winsize = 1 if rnd.randint(0, 1) == 0 else 2\r\n ndups = len(easy) // 8 if winsize == 1 else len(easy) // 11\r\n if ndups != 0 and len(easy) != 0:\r\n idces = set(np.random.choice(len(easy), size=(ndups,), replace=False))\r\n outsent = []\r\n for idx, word in enumerate(easy):\r\n wrd = ' '.join(easy[idx:idx + winsize])\r\n reword = wrd + ' ' + wrd.split()[0] if idx in idces else word\r\n outsent.append(reword)\r\n fouts2t.append(' '.join(outsent))\r\n elif ndups == 0:\r\n fouts2t.append(e.strip())\r\n\r\n return fouts2t\r\n\r\n\r\ndef dropnoise(fd):\r\n foutt2s = []\r\n for d in fd:\r\n # create fktrg2src\r\n diffi = d.strip().split()\r\n winsize = 1\r\n ndups = len(diffi) // 8 if winsize == 1 else len(diffi) // 11\r\n if ndups != 0 and len(diffi) != 0:\r\n idces = set(np.random.choice(len(diffi), size=(ndups,), replace=False))\r\n outsent = []\r\n for idx, word in enumerate(diffi):\r\n wrd = ' '.join(diffi[idx:idx + winsize])\r\n if idx not in idces:\r\n outsent.append(wrd)\r\n foutt2s.append(' '.join(outsent))\r\n elif ndups == 0:\r\n foutt2s.append(d.strip())\r\n return foutt2s\r\n\r\n\r\ndef hasNumbers(inputString):\r\n return any(char.isdigit() for char in inputString)\r\n\r\n\r\ndef wordordernoise(sents, noiseratio):\r\n sents = [sent.strip().split() for sent in sents]\r\n lengths = [len(sent) for sent in sents]\r\n for idx, length in enumerate(lengths):\r\n if length > 5:\r\n for it in range(int(noiseratio * length)):\r\n j = rnd.randint(0, length - 2)\r\n sents[idx][j], sents[idx][j + 1] = sents[idx][j + 1], sents[idx][j]\r\n return [' '.join(sent) for sent in sents]\r\n\r\n\r\ndef additive_noise(sent_batch,\r\n lengths,\r\n corpus,\r\n ae_add_noise_perc_per_sent_low,\r\n ae_add_noise_perc_per_sent_high,\r\n ae_add_noise_num_sent,\r\n ae_add_noise_2_grams):\r\n assert ae_add_noise_perc_per_sent_low <= ae_add_noise_perc_per_sent_high\r\n batch_size = len(lengths)\r\n if ae_add_noise_2_grams:\r\n shuffler_func = operations.shuffle_2_grams\r\n else:\r\n shuffler_func = operations.shuffle\r\n split_sent_batch = [\r\n sent.split()\r\n for sent in sent_batch\r\n ]\r\n length_arr = np.array(lengths)\r\n min_add_lengths = np.floor(length_arr * ae_add_noise_perc_per_sent_low)\r\n max_add_lengths = np.ceil(length_arr * ae_add_noise_perc_per_sent_high)\r\n for s_i in range(ae_add_noise_num_sent):\r\n add_lengths = np.round(\r\n np.random.uniform(min_add_lengths, max_add_lengths)\r\n ).astype(int)\r\n next_batch = operations.shuffle(corpus.next_batch(batch_size))\r\n for r_i, new_sent in enumerate(next_batch):\r\n addition = shuffler_func(new_sent.split())[:add_lengths[r_i]]\r\n split_sent_batch[r_i] += addition\r\n noised_sent_batch = [\r\n \" \".join(shuffler_func(sent))\r\n for sent in split_sent_batch\r\n ]\r\n return noised_sent_batch\r\n\r\n\r\ndef numberfiltering(sents):\r\n # replace any word with numbers in it as \r\n sents = [sent.strip().split() for sent in sents]\r\n for idx in range(len(sents)):\r\n for pos in range(len(sents[idx])):\r\n if hasNumbers(sents[idx][pos]):\r\n sents[idx][pos] = 'BlahBlah'\r\n # print(sents)\r\n return [' '.join(sent) for sent in sents]\r\n\r\n\r\n","sub_path":"noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"83688575","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('fileindex', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Photo',\n fields=[\n ('indexedfile_ptr', models.OneToOneField(to='fileindex.IndexedFile', auto_created=True, primary_key=True, serialize=False, parent_link=True, on_delete=models.CASCADE)),\n ],\n bases=('fileindex.indexedfile',),\n ),\n ]\n","sub_path":"photoindex/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"337748668","text":"#!/usr/bin/python\n# coding: utf8\nprint(__doc__)\nfrom numpy import *\n\n# 加载数据集\ndef loadDataSet():\n return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]\n\n# 创建集合 C1。即对 dataSet 进行去重,排序,放入 list 中,然后转换所有的元素为 frozenset\ndef createC1(dataSet):\n \"\"\"createC1(创建集合 C1)\n\n Args:\n dataSet 原始数据集\n Returns:\n frozenset 返回一个 frozenset 格式的 list\n \"\"\"\n\n C1 = []\n for transaction in dataSet:\n for item in transaction:\n if not [item] in C1:\n # 遍历所有的元素,如果不在 C1 出现过,那么就 append\n C1.append([item])\n # 对数组进行 `从小到大` 的排序\n # print 'sort 前=', C1\n C1.sort()\n # frozenset 表示冻结的 set 集合,元素无改变;可以把它当字典的 key 来使用\n # print 'sort 后=', C1\n # print 'frozenset=', map(frozenset, C1)\n return list(map(frozenset, C1))\n\n# 计算候选数据集 CK 在数据集 D 中的支持度,并返回支持度大于最小支持度(minSupport)的数据\ndef scanD(D, Ck, minSupport):\n \"\"\"scanD(计算候选数据集 CK 在数据集 D 中的支持度,并返回支持度大于最小支持度 minSupport 的数据)\n\n Args:\n D 数据集\n Ck 候选项集列表\n minSupport 最小支持度\n Returns:\n retList 支持度大于 minSupport 的集合\n supportData 候选项集支持度数据\n \"\"\"\n\n # ssCnt 临时存放选数据集 Ck 的频率. 例如: a->10, b->5, c->8 \n ssCnt = {}\n for tid in D:\n for can in Ck:\n # s.issubset(t) 测试是否 s 中的每一个元素都在 t 中\n if can.issubset(tid):\n # if not ssCnt.has_key(can):\n if can not in ssCnt.keys():\n ssCnt[can] = 1\n else:\n ssCnt[can] += 1\n numItems = float(len(D)) # 数据集 D 的数量\n retList = []\n supportData = {}\n for key in ssCnt:\n # 支持度 = 候选项(key)出现的次数 / 所有数据集的数量\n support = ssCnt[key]/numItems\n if support >= minSupport:\n # 在 retList 的首位插入元素,只存储支持度满足频繁项集的值\n retList.insert(0, key)\n # 存储所有的候选项(key)和对应的支持度(support)\n supportData[key] = support\n return retList, supportData\n\n# 输入频繁项集列表 Lk 与返回的元素个数 k,然后输出所有可能的候选项集 Ck\ndef aprioriGen(Lk, k):\n \"\"\"aprioriGen(输入频繁项集列表 Lk 与返回的元素个数 k,然后输出候选项集 Ck。\n 例如: 以 {0},{1},{2} 为输入且 k = 2 则输出 {0,1}, {0,2}, {1,2}. 以 {0,1},{0,2},{1,2} 为输入且 k = 3 则输出 {0,1,2}\n 仅需要计算一次,不需要将所有的结果计算出来,然后进行去重操作\n 这是一个更高效的算法)\n\n Args:\n Lk 频繁项集列表\n k 返回的项集元素个数(若元素的前 k-2 相同,就进行合并)\n Returns:\n retList 元素两两合并的数据集\n \"\"\"\n \n retList = []\n lenLk = len(Lk)\n for i in range(lenLk):\n for j in range(i+1, lenLk):\n L1 = list(Lk[i])[: k-2]\n L2 = list(Lk[j])[: k-2]\n # print '-----i=', i, k-2, Lk, Lk[i], list(Lk[i])[: k-2]\n # print '-----j=', j, k-2, Lk, Lk[j], list(Lk[j])[: k-2]\n L1.sort()\n L2.sort()\n # 第一次 L1,L2 为空,元素直接进行合并,返回元素两两合并的数据集\n # if first k-2 elements are equal\n if L1 == L2:\n # set union\n # print 'union=', Lk[i] | Lk[j], Lk[i], Lk[j]\n retList.append(Lk[i] | Lk[j])\n return retList\n\n# 找出数据集 dataSet 中支持度 >= 最小支持度的候选项集以及它们的支持度。即我们的频繁项集。\ndef apriori(dataSet, minSupport=0.5):\n \"\"\"apriori(首先构建集合 C1,然后扫描数据集来判断这些只有一个元素的项集是否满足最小支持度的要求。那么满足最小支持度要求的项集构成集合 L1。然后 L1 中的元素相互组合成 C2,C2 再进一步过滤变成 L2,然后以此类推,知道 CN 的长度为 0 时结束,即可找出所有频繁项集的支持度。)\n\n Args:\n dataSet 原始数据集\n minSupport 支持度的阈值\n Returns:\n L 频繁项集的全集\n supportData 所有元素和支持度的全集\n \"\"\"\n # C1 即对 dataSet 进行去重,排序,放入 list 中,然后转换所有的元素为 frozenset\n C1 = createC1(dataSet)\n # print 'C1: ', C1\n # 对每一行进行 set 转换,然后存放到集合中\n D = dataSet\n # print 'D=', D\n # 计算候选数据集 C1 在数据集 D 中的支持度,并返回支持度大于 minSupport 的数据\n L1, supportData = scanD(D, C1, minSupport)\n # print \"L1=\", L1, \"\\n\", \"outcome: \", supportData\n\n # L 加了一层 list, L 一共 2 层 list\n L = [L1]\n k = 2\n # 判断 L 的第 k-2 项的数据长度是否 > 0。第一次执行时 L 为 [[frozenset([1]), frozenset([3]), frozenset([2]), frozenset([5])]]。L[k-2]=L[0]=[frozenset([1]), frozenset([3]), frozenset([2]), frozenset([5])],最后面 k += 1\n while (len(L[k-2]) > 0):\n # print 'k=', k, L, L[k-2]\n Ck = aprioriGen(L[k-2], k) # 例如: 以 {0},{1},{2} 为输入且 k = 2 则输出 {0,1}, {0,2}, {1,2}. 以 {0,1},{0,2},{1,2} 为输入且 k = 3 则输出 {0,1,2}\n # print 'Ck', Ck\n\n Lk, supK = scanD(D, Ck, minSupport) # 计算候选数据集 CK 在数据集 D 中的支持度,并返回支持度大于 minSupport 的数据\n # 保存所有候选项集的支持度,如果字典没有,就追加元素,如果有,就更新元素\n supportData.update(supK)\n if len(Lk) == 0:\n break\n # Lk 表示满足频繁子项的集合,L 元素在增加,例如: \n # l=[[set(1), set(2), set(3)]]\n # l=[[set(1), set(2), set(3)], [set(1, 2), set(2, 3)]]\n L.append(Lk)\n k += 1\n # print 'k=', k, len(L[k-2])\n return L, supportData\n\n# 计算可信度(confidence)\ndef calcConf(freqSet, H, supportData, brl, minConf=0.7):\n \"\"\"calcConf(对两个元素的频繁项,计算可信度,例如: {1,2}/{1} 或者 {1,2}/{2} 看是否满足条件)\n\n Args:\n freqSet 频繁项集中的元素,例如: frozenset([1, 3]) \n H 频繁项集中的元素的集合,例如: [frozenset([1]), frozenset([3])]\n supportData 所有元素的支持度的字典\n brl 关联规则列表的空数组\n minConf 最小可信度\n Returns:\n prunedH 记录 可信度大于阈值的集合\n \"\"\"\n # 记录可信度大于最小可信度(minConf)的集合\n prunedH = []\n for conseq in H: # 假设 freqSet = frozenset([1, 3]), H = [frozenset([1]), frozenset([3])],那么现在需要求出 frozenset([1]) -> frozenset([3]) 的可信度和 frozenset([3]) -> frozenset([1]) 的可信度\n\n # print 'confData=', freqSet, H, conseq, freqSet-conseq\n conf = supportData[freqSet]/supportData[freqSet-conseq] # 支持度定义: a -> b = support(a | b) / support(a). 假设 freqSet = frozenset([1, 3]), conseq = [frozenset([1])],那么 frozenset([1]) 至 frozenset([3]) 的可信度为 = support(a | b) / support(a) = supportData[freqSet]/supportData[freqSet-conseq] = supportData[frozenset([1, 3])] / supportData[frozenset([1])]\n if conf >= minConf:\n # 只要买了 freqSet-conseq 集合,一定会买 conseq 集合(freqSet-conseq 集合和 conseq集合 是全集)\n print (freqSet-conseq, '-->', conseq, 'conf:', conf)\n brl.append((freqSet-conseq, conseq, conf))\n prunedH.append(conseq)\n return prunedH\n\n# 递归计算频繁项集的规则\ndef rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):\n \"\"\"rulesFromConseq\n\n Args:\n freqSet 频繁项集中的元素,例如: frozenset([2, 3, 5]) \n H 频繁项集中的元素的集合,例如: [frozenset([2]), frozenset([3]), frozenset([5])]\n supportData 所有元素的支持度的字典\n brl 关联规则列表的数组\n minConf 最小可信度\n \"\"\"\n # H[0] 是 freqSet 的元素组合的第一个元素,并且 H 中所有元素的长度都一样,长度由 aprioriGen(H, m+1) 这里的 m + 1 来控制\n # 该函数递归时,H[0] 的长度从 1 开始增长 1 2 3 ...\n # 假设 freqSet = frozenset([2, 3, 5]), H = [frozenset([2]), frozenset([3]), frozenset([5])]\n # 那么 m = len(H[0]) 的递归的值依次为 1 2\n # 在 m = 2 时, 跳出该递归。假设再递归一次,那么 H[0] = frozenset([2, 3, 5]),freqSet = frozenset([2, 3, 5]) ,没必要再计算 freqSet 与 H[0] 的关联规则了。\n m = len(H[0])\n if (len(freqSet) > (m + 1)):\n # print 'freqSet******************', len(freqSet), m + 1, freqSet, H, H[0]\n # 生成 m+1 个长度的所有可能的 H 中的组合,假设 H = [frozenset([2]), frozenset([3]), frozenset([5])]\n # 第一次递归调用时生成 [frozenset([2, 3]), frozenset([2, 5]), frozenset([3, 5])]\n # 第二次 。。。没有第二次,递归条件判断时已经退出了\n Hmp1 = aprioriGen(H, m+1)\n # 返回可信度大于最小可信度的集合\n Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)\n print ('Hmp1=', Hmp1)\n print ('len(Hmp1)=', len(Hmp1), 'len(freqSet)=', len(freqSet))\n # 计算可信度后,还有数据大于最小可信度的话,那么继续递归调用,否则跳出递归\n if (len(Hmp1) > 1):\n # print '----------------------', Hmp1\n # print len(freqSet), len(Hmp1[0]) + 1\n rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)\n\n# 生成关联规则\ndef generateRules(L, supportData, minConf=0.7):\n \"\"\"generateRules\n\n Args:\n L 频繁项集列表\n supportData 频繁项集支持度的字典\n minConf 最小置信度\n Returns:\n bigRuleList 可信度规则列表(关于 (A->B+置信度) 3个字段的组合)\n \"\"\"\n bigRuleList = []\n # 假设 L = [[frozenset([1]), frozenset([3]), frozenset([2]), frozenset([5])], [frozenset([1, 3]), frozenset([2, 5]), frozenset([2, 3]), frozenset([3, 5])], [frozenset([2, 3, 5])]]\n for i in range(1, len(L)):\n # 获取频繁项集中每个组合的所有元素\n for freqSet in L[i]:\n # 假设:freqSet= frozenset([1, 3]), H1=[frozenset([1]), frozenset([3])]\n # 组合总的元素并遍历子元素,并转化为 frozenset 集合,再存放到 list 列表中\n H1 = [frozenset([item]) for item in freqSet]\n # 2 个的组合,走 else, 2 个以上的组合,走 if\n if (i > 1):\n rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)\n else:\n calcConf(freqSet, H1, supportData, bigRuleList, minConf)\n return bigRuleList\n\n\ndef getActionIds():\n from time import sleep\n from votesmart import votesmart\n # votesmart.apikey = 'get your api key first'\n votesmart.apikey = 'a7fa40adec6f4a77178799fae4441030'\n actionIdList = []\n billTitleList = []\n fr = open('../db/11.Apriori/recent20bills.txt')\n for line in fr.readlines():\n billNum = int(line.split('\\t')[0])\n try:\n billDetail = votesmart.votes.getBill(billNum) # api call\n for action in billDetail.actions:\n if action.level == 'House' and (action.stage == 'Passage' or action.stage == 'Amendment Vote'):\n actionId = int(action.actionId)\n print ('bill: %d has actionId: %d' % (billNum, actionId))\n actionIdList.append(actionId)\n billTitleList.append(line.strip().split('\\t')[1])\n except:\n print (\"problem getting bill %d\" % billNum)\n sleep(1) # delay to be polite\n return actionIdList, billTitleList\n\n\ndef getTransList(actionIdList, billTitleList): #this will return a list of lists containing ints\n itemMeaning = ['Republican', 'Democratic']#list of what each item stands for\n for billTitle in billTitleList:#fill up itemMeaning list\n itemMeaning.append('%s -- Nay' % billTitle)\n itemMeaning.append('%s -- Yea' % billTitle)\n transDict = {}#list of items in each transaction (politician)\n voteCount = 2\n for actionId in actionIdList:\n sleep(3)\n print ('getting votes for actionId: %d' % actionId)\n try:\n voteList = votesmart.votes.getBillActionVotes(actionId)\n for vote in voteList:\n if not transDict.has_key(vote.candidateName):\n transDict[vote.candidateName] = []\n if vote.officeParties == 'Democratic':\n transDict[vote.candidateName].append(1)\n elif vote.officeParties == 'Republican':\n transDict[vote.candidateName].append(0)\n if vote.action == 'Nay':\n transDict[vote.candidateName].append(voteCount)\n elif vote.action == 'Yea':\n transDict[vote.candidateName].append(voteCount + 1)\n except:\n print (\"problem getting actionId: %d\" % actionId)\n voteCount += 2\n return transDict, itemMeaning\n\n\n# 暂时没用上\n# def pntRules(ruleList, itemMeaning):\n# for ruleTup in ruleList:\n# for item in ruleTup[0]:\n# print itemMeaning[item]\n# print \" -------->\"\n# for item in ruleTup[1]:\n# print itemMeaning[item]\n# print \"confidence: %f\" % ruleTup[2]\n# print #print a blank line\n\ndef testApriori():\n # 加载测试数据集\n dataSet = loadDataSet()\n print ('dataSet: ', dataSet)\n\n # Apriori 算法生成频繁项集以及它们的支持度\n L1, supportData1 = apriori(dataSet, minSupport=0.7)\n print ('L(0.7): ', L1)\n print ('supportData(0.7): ', supportData1)\n\n print ('->->->->->->->->->->->->->->->->->->->->->->->->->->->->')\n\n # Apriori 算法生成频繁项集以及它们的支持度\n L2, supportData2 = apriori(dataSet, minSupport=0.5)\n print ('L(0.5): ', L2)\n print ('supportData(0.5): ', supportData2)\n\ndef testGenerateRules():\n # 加载测试数据集\n dataSet = loadDataSet()\n print ('dataSet: ', dataSet)\n\n # Apriori 算法生成频繁项集以及它们的支持度\n L1, supportData1 = apriori(dataSet, minSupport=0.5)\n print ('L(0.7): \\n', L1)\n print ('supportData(0.7):\\n ', supportData1)\n\n # 生成关联规则\n rules = generateRules(L1, supportData1, minConf=0.5)\n print ('rules:\\n ', rules)\n\ndef main():\n # 测试 Apriori 算法\n # testApriori()\n\n # 生成关联规则\n # testGenerateRules()\n\n ##项目案例\n # # 构建美国国会投票记录的事务数据集\n # actionIdList, billTitleList = getActionIds()\n # # 测试前2个\n # transDict, itemMeaning = getTransList(actionIdList[: 2], billTitleList[: 2])\n #transDict 表示 action_id的集合,transDict[key]这个就是action_id对应的选项,例如 [1, 2, 3]\n # transDict, itemMeaning = getTransList(actionIdList, billTitleList)\n # # 得到全集的数据\n # dataSet = [transDict[key] for key in transDict.keys()]\n # L, supportData = apriori(dataSet, minSupport=0.3)\n # rules = generateRules(L, supportData, minConf=0.95)\n # print (rules)\n\n # # 项目案例\n # # 发现毒蘑菇的相似特性\n # # 得到全集的数据\n dataSet = [line.split() for line in open(\"../db/11.Apriori/mushroom.dat\").readlines()]\n L, supportData = apriori(dataSet, minSupport=0.3)\n # # 2表示毒蘑菇,1表示可食用的蘑菇\n # # 找出关于2的频繁子项出来,就知道如果是毒蘑菇,那么出现频繁的也可能是毒蘑菇\n for item in L[1]:\n if item.intersection('2'):\n print (item)\n \n for item in L[2]:\n if item.intersection('2'):\n print (item)\n\nif __name__ == \"__main__\":\n # main()\n # testApriori()\n testGenerateRules()\n","sub_path":"13关联分析/apriori_ys.py","file_name":"apriori_ys.py","file_ext":"py","file_size_in_byte":16406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"439084553","text":"from gettvshow import gettvshow\nfrom channeladdr import channeladdr,tags\nfrom my_time import timelength_\nfrom channelname import name_normalize\ndef gettags(start,end,channel,number):#给用户的每个收视时段所观看的电视节目所进行的标签\n channel = name_normalize(channel)\n start = str(start)\n end = str(end)\n if channel in channeladdr:\n try:\n showlist = gettvshow(start,end,channel)#Excel附件原始形式的参数\n except:\n print(start,end,channel)\n pass#利用豆瓣对所看节目进行标签,并对标签进行时长累加,返回([标签,时长])\n return 0\n elif channel in tags:\n lbas = []#label and scores\n for tag in tags[channel]:\n lbas.append([tag,timelength_(start,end)])\n return lbas\n else:\n print('无与'+channel+'相关的数据!')\n return 0\ndef givetags(dic,account,tags):#给每个用户贴上标签\n if not account in dic:\n dic[account] = {}\n for tag in tags:\n if tag[0] in dic[account]:\n dic[account][tag[0]] = dic[account][tag[0]] + tag[1]\n else:\n dic[account][tag[0]] = tag[1]\n return dic\n","sub_path":"雷打不动的论文和附件/提交的附件/别点/千万别点/附件/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"515433745","text":"# global imports\nfrom Tkinter import *\nimport ttk\nimport os\n\n# own imports\nimport Plugins\n\n# create master and main widget\nmaster = Tk()\nprogram_name = \"La Paella\"\nmaster.wm_title(program_name)\nmaster.overrideredirect(1)\n\n# frame_time, used to control timers by doing frame_time % == 0\n# can also be used to know the ammount of frames the program has played\nframe_time = 0\nsmooth_value = 0\nglobal_timer = 0\nupdated = False\nnew_created = True\nlast_geometry = Plugins.ProgramGetSize(master)\nnew_geometry = last_geometry\nglobal_username = \"__USERNAME__\"\n\n#colors\nprogram_bg = \"#2980b9\"\nprogram_border = \"#1c567d\"\nprogram_border_dark = \"#123a54\"\n\n#widgets\nprogram_bg_clear_fg = \"#2e90d1\"\nprogram_bg_dark_fg = \"#52a7e0\"\n\nprogram_fg_clear_bg = \"#2c3e50\"\nprogram_fg_dark_bg = \"#34495e\"\n\nprogram_clear = \"#ffffff\"\n\n#set program window background color\nmaster[\"bg\"]=program_bg\nmain_border=Frame(master, bg=program_border)\ntop_bar = Frame(main_border, bg=program_border)\ntop_bar_name = Label(top_bar, text=program_name, bg=program_border, fg=program_clear)\ntop_bar_icon_image = PhotoImage(file=\"data/icon/icon_16x16.gif\")\nprogram_icon_image = PhotoImage(file=\"data/icon/icon_196x196.gif\")\ntop_bar_icon = Label(top_bar, text=\"\", image=top_bar_icon_image, bg=program_border)\ntop_bar_icon.pack(side=LEFT)\n#move window with top_bar if clicked\ntop_bar.bind(\"\", lambda x: Plugins.ProgramDragWithMouse(master, x))\ntop_bar_name.bind(\"\", lambda x: Plugins.ProgramDragWithMouse(master, x))\ntop_bar_name.pack(side=LEFT, fill=X, expand=YES)\n#functions\ndef ProgramEnd(frame = None):\n os._exit(1)\n \ndef ReloadIndexesInListbox(new_value, target_list):\n pass\n\nclose_button = Button(top_bar, text=\"x\", command=lambda: ProgramEnd(),\n bg=program_border_dark, fg=\"white\", bd=0,\n highlightthickness=0)\n\ndef main(status = \"Login\"):\n global last_geometry, new_geometry, updated, new_created\n \n main_frame = Frame(main_border, bg=program_bg)\n program_status = status\n #Misc Functions\n def UnbindWheel(widget):\n widget.bind(\"\", DoNothing) # windows and mac\n widget.bind(\"\", DoNothing) # linux specific\n widget.bind(\"\", DoNothing) # linux specific\n \n def DoNothing(event):\n return \"break\"\n\n #constants and program-based value\n user_list = {\n 0: \"Juan Perez\",\n 1: \"Lucas Rojas\",\n 2: \"Rodrigo Mesa\",\n 3: \"Pedro Palma\",\n 4: \"Amarando Cortez\",\n 5: \"Javier Astorga\",\n 6: \"Ignacio Rivero\",\n 7: \"Carlos Gomez\",\n 8: \"Federico Santamaria\",\n 9: \"Antonio Rios\",\n 10: \"Cesar Bustamante\",\n 11: \"Esteban Soto\",\n 12: \"Marisol Tapia\",\n }\n for i in range(1000):\n user_list[i+12] = \"User\"+str(i)\n \n user_list_length = len(user_list.keys())\n\n # no matter the program_status, there is a menu, if a program_status \n # needs tohide it, there is a config for it\n menu0 = Menu(main_frame)\n #master.config(menu=menu0)\n\n def hello(): pass\n\n filemenu = Menu(menu0, tearoff=0)\n filemenu.add_command(label=\"Open\", command=hello)\n filemenu.add_command(label=\"Save\", command=hello)\n filemenu.add_separator()\n filemenu.add_command(label=\"Exit\", command=lambda: ProgramEnd(main_frame))\n menu0.add_cascade(label=\"File\", menu=filemenu)\n\n # setup widgets based on program_status\n if program_status == \"Login\":\n label0 = Label(main_frame, text=\"Bienvenido a\", font=(\"Mono\", 16),\n bg=program_bg)\n label1 = Label(main_frame, text=program_name, font=(\"Mono\", 24),\n bg=program_bg)\n label2 = Label(main_frame, text=\"Elija su usuario de la lista:\",\n font=(\"Sans\", 12), bg=program_bg)\n \n label3 = Label(main_frame, text=\"Elija fuente de\",\n font=(\"Sans\", 12), bg=program_bg)\n label4 = Label(main_frame, text=\"usuarios y peliculas:\",\n font=(\"Sans\", 12), bg=program_bg)\n \n program_icon = Label(main_frame, text=\"\", image=program_icon_image,\n bg=program_bg, borderwidth=0)\n \n option_val = StringVar()\n option_list = [\"MovieLens 10M Dataset\", \"Small Dataset\"]\n option = OptionMenu(main_frame, option_val, *option_list,\n command=None)\n option[\"menu\"].config(bg=program_bg, fg=program_clear,\n activebackground=program_bg)\n option.config(bg=program_bg, fg=program_clear, relief=FLAT,\n highlightthickness=0, ) \n \n option_val.set(option_list[0])\n \n listbox0 = Listbox(main_frame, relief=FLAT, selectmode=SINGLE, bd=0,\n highlightthickness=0)\n \n scale0 = Scale(main_frame, from_=0, to_=100, orient=\"vertical\",\n showvalue=0, borderwidth=0, sliderrelief=FLAT,\n highlightcolor=program_bg, highlightthickness=0)\n \n bf = Frame(main_frame, bg=program_bg)\n bf_left = Frame(bf, bg=program_bg)\n bf_right = Frame(bf, bg=program_bg)\n \n button0 = Button(bf_left, text=\"Login\", relief=FLAT,\n command=lambda: ProgramSwitchMode(\"Loading\"),\n bg=program_bg, highlightthickness=0)\n button1 = Button(bf_right, text=\"Exit\", relief=FLAT,\n command=lambda: ProgramEnd(main_frame),\n bg=program_bg, highlightthickness=0)\n \n button2_value = option_list[0]\n button2 = Button(main_frame, text=\"Aplicar cambios...\", relief=FLAT,\n command=lambda: ReloadIndexesInListbox(button2_value, listbox0), \n bg=program_bg, highlightthickness=0)\n \n label0.grid(row=0, padx=8)\n label1.grid(row=1, padx=8, pady=(0, 8))\n label2.grid(row=5, padx=8, sticky=W)\n \n program_icon.grid(row=2)\n \n label3.grid(row=3, padx=8, sticky=W)\n option.grid(row=5, sticky=W+E, padx=8)\n label4.grid(row=4, padx=8, sticky=W)\n button2.grid(row=6, padx=8, sticky=W+E)\n \n listbox0.grid(row=7, padx=(8,26), pady=(12,4), sticky=W+E)\n scale0.grid(row=7, padx=(0, 8), pady=(12, 4), sticky=E+N+S)\n \n bf.grid(row=8, sticky=W+E)\n bf_left.pack(fill=BOTH, expand=YES, side=LEFT, padx=(8, 0), pady=4)\n bf_right.pack(fill=BOTH, expand=YES, side=RIGHT, padx=(0, 8), pady=4)\n\n button0.pack(fill=BOTH)\n button1.pack(fill=BOTH)\n \n UnbindWheel(listbox0)\n for user_id, user in user_list.items():\n listbox0.insert(END, str(user))\n for i in range(len(user_list)):\n #colour items based on modulo\n try:\n if i%2==0:\n color = program_bg_clear_fg\n color2 = program_fg_dark_bg\n else:\n color = program_bg_dark_fg\n color2 = program_fg_clear_bg\n listbox0.itemconfig(i, {'bg':color, \"fg\":color2})\n except:\n break\n \n elif program_status == \"Loading\":\n #design Loading screen\n label0 = Label(main_frame, text=\"Loading content...\",\n font=(\"Monospaced\", 24), bg=program_bg)\n (animation0, \n animation0_list, \n animation0_len) = Plugins.GetAnimationFromGif(main_frame, \"data/running.gif\")\n \n animation0.config(bg=program_bg)\n label0.grid(row=0)\n animation0.grid(row=1, pady=8)\n\n elif program_status == \"TopTen\":\n labeluser = Label(main_frame, text=\"Bienvenido: \"+str(global_username),\n font=(\"Serif\", 22), bg=program_bg)\n label0 = Label(main_frame, text=\"Estas son las 10 peliculas\\nrecomendadas para usted!\",\n font=(\"Serif\", 16), bg=program_bg)\n data_frame = Frame(main_frame, bg=program_bg)\n count, count_list, count_len = Plugins.GetAnimationFromGif(main_frame, \"data/countdown.gif\") \n count[\"bg\"] = program_bg\n scale0 = Scale(main_frame, orient=\"horizontal\", showvalue=0, relief=FLAT,\n borderwidth=0, from_=0, to=9, sliderrelief=FLAT,\n highlightthickness=0)\n\n label1 = Label(data_frame, text=\" \"*20, font=(\"Mono\", 16), bg=program_bg)\n label2 = Label(data_frame, text=\"\", font=(\"Serif\", 12), bg=program_bg)\n label3 = Label(data_frame, text=\"\", font=(\"Serif\", 12), bg=program_bg)\n \n label4 = Label(main_frame, text=\"+1;\", font=(\"Arial Black\", 24), bg=\"#181818\", fg=\"white\")\n \n button0 = Button(main_frame, text=\"Volver Atras!\",\n command=lambda: ProgramSwitchMode(\"Login\"),\n highlightthickness=0)\n \n labeluser.grid(row=0, columnspan=2, padx=8)\n label0.grid(row=1, columnspan=2)\n label1.pack(fill=BOTH, padx=8)\n label2.pack(fill=X, padx=8)\n label3.pack(fill=X, padx=8)\n \n data_frame.grid(row=2, column=1, sticky=N+S+W+E)\n \n count.grid(row=2, padx=8)\n label4.grid(row=2, sticky=E,padx=12) #topkek\n scale0.grid(row=3, sticky=W+E, padx=8)\n button0.grid(row=3, column=1, padx=8, pady=4, sticky=W+E)\n\n #allow for ProgramUpdateWidgets to modify widgets properties\n updated = True\n \n #UpdateStep function\n def ProgramUpdateWidgets():\n global frame_time, global_timer, smooth_value\n # get program size\n program_width, program_height = master.winfo_width(), master.winfo_height()\n frame_time += 1\n #master.update()\n master.geometry(\"\")\n \n #dont update if no widgets exists\n if updated == False:\n return 0\n try:\n if program_status == \"None\":\n ProgramEnd(main_frame)\n \n if program_status == \"Login\":\n global global_username\n #set scale0 based on listbox0 length\n user_list_length = len(user_list)\n listbox0_max = max(user_list_length - int(listbox0[\"height\"]), 0)\n scale0.config(to=listbox0_max, resolution=0.01)\n \n #set listbox position based on scale\n listbox0_y = int(round(scale0.get() ))\n listbox0.yview(listbox0_y)\n \n global_username = listbox0.get(ACTIVE) \n \n elif program_status == \"Loading\":\n animation0.config(image=animation0_list[(frame_time/400)%animation0_len])\n if frame_time%100 == 0:\n global_timer += 1\n if global_timer >= 200:\n global_timer = 0\n ProgramSwitchMode(\"TopTen\")\n \n elif program_status == \"TopTen\":\n tenth = (count_len)/10.0\n value = tenth * float(scale0.get())\n smooth_value += (value - smooth_value)/1000.0\n \n count.config(image=count_list[int(smooth_value%count_len)])\n \n label1.config(text=str(\"Movie Number \"+str(10-scale0.get())+\": \").center(20))\n label2.config(text=\"sframe: \"+str(round(smooth_value,2)))\n label3.config(text=\"frame: \"+str(value))\n except:\n return 0\n \n def ProgramSwitchMode(mode=\"Loading\"):\n global updated, last_geometry\n last_geometry = Plugins.ProgramGetSize(master)\n main_frame.destroy()\n updated = False\n main(mode)\n \n\n # show main_frame, no longer available to edit\n close_button.pack(side=RIGHT)\n top_bar.pack(fill=BOTH)\n main_frame.pack(fill=BOTH, padx=4, pady=(0,4))\n main_border.pack(fill=BOTH)\n # resize program\n master.update()\n master.geometry(\"\")\n master.update()\n if new_created:\n last_geometry = Plugins.ProgramGetSize(master)\n new_created = False\n else:\n master.update()\n new_geometry = Plugins.ProgramGetSize(master)\n Plugins.ProgramResizeSmooth(master, last_geometry, new_geometry)\n #print last_geometry, new_geometry\n \n # main loop\n master.resizable(width=False, height=False)\n master.protocol(\"WM_DELETE_WINDOW\", lambda: ProgramEnd(master))\n while True:\n master.after(1000/60, lambda: ProgramUpdateWidgets())\n master.update()\n\nif __name__ == \"__main__\":\n main(\"Login\")\n","sub_path":"UI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"463297474","text":"# This is my first python application.\r\n# In this app you have to give numbers. After giving numbers you have to enter any non numeric value.\r\n# Then it will start the calculation process.\r\n\r\n\r\nList = []\r\nprint('Please start giving me numbers, I will start calculating as soon as you give me a non integer value')\r\nwhile True:\r\n value = input('Enter a number- ')\r\n try:\r\n value = float(value)\r\n except:\r\n break\r\n List.append(value)\r\nup = 0\r\nfor var in List:\r\n up += var\r\nprint(float(up/len(List)))\r\ninput('Press enter to close program...')\r\n","sub_path":"Average-Calculator.py","file_name":"Average-Calculator.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"484767843","text":"##### Adam Mansuri \r\n\r\nimport time\r\nimport math\r\nimport sys\r\n\r\n\r\n### These are the tiles with the frogs and toads in their original positions\r\ntileList= ['F','F','F',' ','T','T','T']\r\n\r\n\r\n### This code will show a demonstration for the user, so they know how to play the game. This will be presented as a selection in a menu that i will create later on.\r\ndef demonstration():\r\n print(\"The starting positions are: \")\r\n time.sleep(1)\r\n print(\"\")\r\n print(tileList)\r\n time.sleep(1)\r\n print(\"\")\r\n print(\"To win, you would have to move like below: \")\r\n time.sleep(1)\r\n print(\"\")\r\n print(3,4,['F','F',' ','F','T','T','T'])\r\n print(5,3,['F','F','T','F',' ', 'T', 'T'])\r\n print(6,5,['F','F','T','F','T',' ','T'])\r\n print(4,6,['F','F','T',' ', 'T', 'F','T'])\r\n print(2,4,['F', ' ', 'T', 'F', 'T', 'F', 'T'])\r\n print(1,2,[' ', 'F','T','F','T','F','T'])\r\n print(3,1,['T','F',' ', 'F', 'T','F', 'T'])\r\n print(5,3,['T','F','T','F',' ', 'F', 'T'])\r\n print(7,5,['T','F','T','F','T','F',' '])\r\n print(6,7,['T','F','T','F','T',' ', 'F'])\r\n print(4,6,['T','F','T',' ', 'T', 'F','F'])\r\n print(2,4,['T',' ','T','F','T','F','F'])\r\n print(3,2,['T','T',' ','F','T','F','F'])\r\n print(5,3,['T','T','T','F', ' ', 'F','F'])\r\n print(4,5,['T','T','T', ' ', 'F','F','F'])\r\n time.sleep(1)\r\n print(\"\")\r\n print(\"You have won!\")\r\n\r\n\r\n### Here i will use a method(function) to declare a method called correctMove and define it so that it has everything to do with when the user enters something correct.\r\n### In this function i will have to define that the user can move into an empty tile next to the current tile or can jump across another frog/toad to the next empty tile.\r\n### the 'tileList', 'fromTile' and 'toTile' will be passed on so i will put them in as the parameters\r\ndef correctMove(tileList,fromTile,toTile):\r\n if tileList[toTile]!=' ':\r\n return False\r\n if tileList[fromTile] == 'F':\r\n if fromTile>toTile or abs(toTile-fromTile)>2:\r\n return False\r\n else:\r\n if fromTile2:\r\n return False\r\n return True\r\n\r\n\r\n### This is a function which will be called when the user wins the game.\r\n### The code looks complex but its simple. It consisted of me creating 2 boolean flags which were originally false then after the piece of code which defined the user to win, the boolean flag change to true.\r\ndef winGame():\r\n flag=False\r\n flag2=False\r\n for i in range(0,3):\r\n if tileList[i] =='F':\r\n flag= True\r\n for i in range(4,len(tileList)):\r\n if tileList[i]=='T':\r\n flag2= True\r\n if flag==True and flag2== True:\r\n return True\r\n\r\n\r\n\r\n### Now i will create a function so that the user can quit the game. Again i will put this in a menu later on\r\ndef quitGame():\r\n print(\"Game Over, You Quit!\")\r\n sys.exit(1)\r\n\r\n\r\n### Now using all the above functions of correctMove and winGame, i will implement them inside the actual game.\r\ndef startGame(tileList):\r\n print(tileList)\r\n print(\"From which tile: \")\r\n fromTile= int(input())-1 ### I did -1 because the list starts from index 0, and i want the user to select a number starting from 1 and not 0\r\n print(\"To which tile: \")\r\n toTile = int(input())-1\r\n\r\n correct=correctMove(tileList,fromTile, toTile)\r\n\r\n if correct:\r\n value= tileList[fromTile]\r\n tileList[toTile]= value\r\n tileList[fromTile] = ' '\r\n print(\"new tileList:\\t\",tileList)\r\n else:\r\n print(\"Invalid jump!\")\r\n\r\n if winGame==True:\r\n print(\"Congratulation, you have won the game!\")\r\n\r\n quitGame()\r\n\r\n\r\n\r\n\r\n### I will create a function so that the user can replay the game. Again i will put this in a menu later on\r\ndef replayGame(tileList):\r\n print(\"Starting positions are: \", tileList)\r\n startGame(tileList)\r\n\r\n### Now i will build a menu to increase user interaction so that they can select one of the 3 choices: 1)demonstration, 2)play the game or 3)quit the game. Hence, these 3 methods will be implemented inside the menu\r\n###For this i will use a while loop which will contain nested if/else statements\r\nwhile True:\r\n print(\"To quit the game press 2\")\r\n print(\"To replay the game press 0\")\r\n print(\"To see the demonstration press 1\")\r\n print(\"Press 3 to continue game!\")\r\n\r\n userSelection= int(input())\r\n\r\n if(userSelection)==2:\r\n quitGame()\r\n elif(userSelection)==0:\r\n replayGame(tileList)\r\n elif(userSelection)==1:\r\n demonstration()\r\n elif(userSelection)==3:\r\n print(\"Lets Continue!\")\r\n startGame(tileList)\r\n else:\r\n print()\r\n","sub_path":"FrogsandToads.py","file_name":"FrogsandToads.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"12667435","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Created by 秋叶夏风\n\n# 本模块的功能:<>\n\n\nimport sys\n\nfrom PyQt5.QtGui import QIcon, QFont\n\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QToolTip\n\napp = QApplication(sys.argv)\nw = QWidget()\nw.setWindowTitle(\"刘金玉编程\")\napp.setWindowIcon(QIcon(\"./images/车.png\"))\nQToolTip.setFont(QFont(\"隶书\",40))\nw.setToolTip(\"编程创造城市\")\n# 按钮\nbtn = QPushButton(\"老刘\",w)\nbtn.move(50,50)\nbtn.setToolTip(\"你好buton\")\nw.show()\n\napp.exec_()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"code/LJYDemo/Demo5/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"346784291","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/marx/venv3/lib/python3.6/site-packages/tsr/modules/general.py\n# Compiled at: 2018-06-27 08:14:39\n# Size of source mod 2**32: 10003 bytes\nimport datetime, json\nfrom .os_info import path\nimport os.path\nfrom dateutil.relativedelta import relativedelta\nusers = {}\nusername_colour_dict = {}\nusername_to_id = {}\nusers = json.load(open(os.path.join(path.settings, 'users.json')))\nfor entry in users:\n if 'colour' not in users[entry]:\n users[entry]['colour'] = 'end'\n\nsettings = json.load(open(os.path.join(path.settings, 'settings.json')))\n\ndef level_domain(level, domain):\n if not is_int(level):\n raise ValueError('level_domain(level_number, domain_string)')\n neglevel = -int(level)\n return '.'.join(domain.split('.')[neglevel:])\n\n\ndef dictfind(original_dict, **kwargs):\n \"\"\" eg\n >>>d={\n 'foo':{\n 'bar': 11,\n 'bob': 'george',\n },\n 'gimli':{\n 'gandalf':{\n 'frodo':5,\n 'samwise':7,\n },\n 'radagast':11,\n },\n 'jones':{\n 'gandalf':{\n 'frodo':1,\n 'samwise':2,\n },\n 'radagast':3,\n },\n }\n >>>find(d, bar='>5')\n ['foo']\n >>>find(d, gandalf_frodo='>3')\n ['gimli']\n \"\"\"\n ListOnlyKeys = True\n if '_ListOnlyKeys' in kwargs:\n ListOnlyKeys = kwargs['_ListOnlyKeys']\n d = dict(original_dict)\n for kw in kwargs:\n if kw[0] != '_':\n kw_value = kwargs[kw]\n kw_relation = None\n if kw_value[0] in ('*', '>', '<', '='):\n kw_relation = kw_value[0]\n kw_value = kw_value[1:]\n kw_relation_end = None\n if kw_value[(-1)] in ('*', ):\n kw_relation_end = kw_value[(-1)]\n kw_value = kw_value[:-1]\n new_d = {}\n key0 = None\n if '_' in kw:\n key0 = kw.split('_')[0]\n key1 = kw.split('_')[1]\n for key in d:\n if key0 in d[key]:\n if key1 in d[key][key0]:\n this_value = d[key][key0][key1]\n if kw_relation == '>':\n kw_value = int(kw_value)\n if this_value > kw_value:\n new_d[key] = d[key]\n else:\n if kw_relation == '<':\n kw_value = int(kw_value)\n if this_value > kw_value:\n new_d[key] = d[key]\n elif kw_relation == '=' and this_value == kw_value:\n pass\n new_d[key] = d[key]\n\n else:\n if kw_relation_end == '*':\n kw_value = kw_value[:-1]\n for key in d:\n if key.startswith(kw_value):\n new_d[key] = d[key]\n\n else:\n if kw_relation == '*':\n kw_value = kw_value\n for key in d:\n if key.endswith(kw_value):\n new_d[key] = d[key]\n\n else:\n if kw_relation == '>':\n kw_value = int(kw_value)\n for key in d:\n if d[key][kw] > kw_value:\n print((' {}>{}'.format(d[key][kw], kw_value)), end='\\r')\n new_d[key] = d[key]\n\n else:\n if kw_relation == '<':\n kw_value = int(kw_value)\n for key in d:\n if d[key][kw] < kw_value:\n new_d[key] = d[key]\n\n else:\n for key in d:\n if d[key][kw] == kw_value:\n new_d[key] = d[key]\n\n d = dict(new_d)\n\n if ListOnlyKeys:\n return [key for key in d]\n else:\n return d\n\n\ndef userid_colour(userid):\n if type(userid) != 'str':\n userid = str(userid)\n try:\n return users[userid]['colour']\n except:\n raise Exception('userid {0} has no colour. users[{0}] = {1}'.format(userid, users[userid]))\n\n\ndef make_n_char_long(x, n, spacing=' '):\n y = str(x)\n while len(y) < n:\n y += spacing\n\n if len(y) > n:\n y = y[:n]\n return y\n\n\ndef myjoin(*args):\n string = ''\n for arg in args:\n string += ' ' + str(arg)\n\n return string[2:]\n\n\ndef standardise_datetime(datestr):\n if isinstance(datestr, datetime.datetime):\n return datestr\n else:\n if isinstance(datestr, datetime.date):\n return datetime.datetime.combine(datestr, datetime.time(0, 0))\n try:\n return datetime.datetime.strptime(datestr, '%d-%m-%Y')\n except:\n try:\n return datetime.datetime.strptime(datestr, '%Y-%m-%d')\n except:\n datestr = datestr.strip().lower()\n if datestr == 'yesterday':\n return datetime.datetime.now() - datetime.timedelta(days=1)\n if 'ago' in datestr:\n date_ls = datestr.split(' ')\n try:\n n = int(date_ls[0])\n formatIs_n_obj_ago = True\n except:\n formatIs_n_obj_ago = False\n\n if formatIs_n_obj_ago:\n date_type = date_ls[1]\n if date_type in ('second', 'seconds'):\n return datetime.datetime.now() - datetime.timedelta(seconds=n)\n if date_type in ('minute', 'minutes'):\n return datetime.datetime.now() - relativedelta(minutes=n)\n if date_type in ('hour', 'hours'):\n return datetime.datetime.now() - relativedelta(hours=n)\n if date_type in ('day', 'days'):\n return datetime.datetime.now() - datetime.timedelta(days=n)\n if date_type in ('week', 'weeks'):\n return datetime.datetime.now() - datetime.timedelta(days=(n * 7))\n if date_type in ('month', 'months'):\n return datetime.datetime.now() - relativedelta(months=n)\n if date_type in ('year', 'years'):\n return datetime.datetime.now() - relativedelta(years=n)\n if date_type in ('decade', 'decades'):\n return datetime.datetime.now() - relativedelta(years=(n * 10))\n else:\n for char in ('T', ' ', '_'):\n if len(datestr) > 18:\n try:\n try:\n datestr = datestr[:19]\n return datetime.datetime.strptime(datestr, '%Y-%m-%d' + char + '%H:%M:%S')\n except:\n datestr = datestr[:19]\n return datetime.datetime.strptime(datestr, '%d-%m-%Y' + char + '%H:%M:%S')\n\n except:\n pass\n\n try:\n try:\n return datetime.datetime.strptime(datestr, '%Y-%m-%d' + char + '%H:%M')\n except:\n return datetime.datetime.strptime(datestr, '%d-%m-%Y' + char + '%H:%M')\n\n except:\n pass\n\n raise Exception('Unknown datetime string: ' + str(datestr))\n\n\ndef standardise_datetime_str(datestr):\n return str(standardise_datetime(datestr))\n\n\ndef standardise_date(string):\n return standardise_datetime(string).date()\n\n\ndef standardise_date_str(datestr):\n return str(standardise_date(datestr))\n\n\ndef standardise_time(timestr):\n return datetime.datetime.strptime(timestr, '%H:%M').time()\n\n\ndef is_number(x):\n try:\n dummy = float(x)\n return True\n except:\n return False\n\n\ndef is_int(x):\n try:\n dummy = int(x)\n return True\n except:\n return False\n\n\ndef ls_rm_dupl(ls):\n l = []\n for x in ls:\n if x not in l:\n l.append(x)\n\n return l\n\n\ndef ls_in_str(ls, string):\n for element in ls:\n try:\n if element in string:\n return True\n except:\n pass\n\n return False\n\n\ndef mystrip(text):\n while ' ' in text:\n text = text.replace(' ', ' ')\n\n while '\\n\\n' in text:\n text = text.replace('\\n\\n', '\\n')\n\n while ' \\n' in text:\n text = text.replace(' \\n', '\\n')\n\n while '\\n ' in text:\n text = text.replace('\\n ', '\\n')\n\n while '\\n> > ' in text:\n text = text.replace('\\n> > ', '\\n> ')\n\n while '>\\n' in text:\n text = text.replace('>\\n', '')\n\n while '~\\n' in text:\n text = text.replace('~\\n', '\\n')\n\n while '\\n\\n' in text:\n text = text.replace('\\n\\n', '\\n')\n\n while '\\r\\n' in text:\n text = text.replace('\\r\\n', '\\n')\n\n while '\\n\\r' in text:\n text = text.replace('\\n\\r', '\\n')\n\n while '\\n\\n' in text:\n text = text.replace('\\n\\n', '\\n')\n\n return text.strip()","sub_path":"pycfiles/tsr-0.0.3.tar/general.cpython-36.py","file_name":"general.cpython-36.py","file_ext":"py","file_size_in_byte":9940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"619046917","text":"import cv2\r\nimport numpy as np\r\nimport pyzbar.pyzbar as pyzbar\r\nglobal abc\r\n\r\ndef main():\r\n cap=cv2.VideoCapture(0)\r\n string=webcam(cap)\r\n print(string)\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\ndef webcam(cap):\r\n while True:\r\n aaa=''\r\n _,frame=cap.read()\r\n decodeObjects=pyzbar.decode(frame)\r\n for obj in decodeObjects:\r\n aaa=obj.data\r\n points=obj.polygon\r\n \r\n \r\n if len(points) > 4: \r\n hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))\r\n hull = list(map(tuple, np.squeeze(hull)))\r\n else: \r\n hull = points;\r\n \r\n \r\n n = len(hull) \r\n for j in range(0,n):\r\n cv2.line(frame, hull[j], hull[ (j+1) % n], (255,0,0), 3)\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n cv2.imshow(\"Frame\",frame)\r\n key=cv2.waitKey(1)\r\n if(key==27):\r\n break\r\n if(len(aaa)>0 and aaa!=''):\r\n abc=str(aaa)\r\n #print(abc)\r\n return(abc)\r\n break\r\n\r\n\r\nmain()","sub_path":"classes/com/thinking/machines/student/application/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"368506749","text":"__author__ = 'Newsteinwell 2015-10-06'\n'''\nThis function read an extant file, this file is included with the same folder, and named \"sampled_data.txt\".\n\nSome operation like gauss filter and sampling with the original data to get sampled_data.\n'''\nimport numpy as np\ndef re_sam_data(FC='FC1'):\n sampled_1=[]\n samp_data=open('sampled_data'+FC+'.txt','r')\n for temp in samp_data:\n temp1=temp.replace('\\n','').split(',')\n sampled_1.append([float(temp1[0]),float(temp1[1])])\n return np.array(sampled_1)\n\ndef re_nonsam_data(FC='FC1'):\n sampled_1=[]\n samp_data=open('nonsampled_data'+FC+'.txt','r')\n for temp in samp_data:\n temp1=temp.replace('\\n','').split(',')\n sampled_1.append([float(temp1[0]),float(temp1[1])])\n return np.array(sampled_1)\n","sub_path":"rvm/read_sam_data.py","file_name":"read_sam_data.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"21290863","text":"import boto3\n\nbucket_name=sys.argv[1]\nRegion_Name=sys.argv[2]\nVersioning=sys.argv[3]\nProject_Name=sys.argv[4]\nTeam=sys.argv[5]\nOwner=sys.argv[6]\nInfra_Owner=sys.argv[7]\nBusiness_Unit=sys.argv[8]\n\n\ns3 = boto3.client('s3')\nresponse = s3.list_buckets()\ncreate_s3=s3.create_bucket(Bucket=bucket_name,CreateBucketConfiguration={'LocationConstraint': Region_Name})\ncreate_tag=s3.put_bucket_tagging(Bucket=bucket_name,Tagging={'TagSet': [{'Key': 'Project_Name','Value': Project_Name},{'Key': 'Team','Value': Team},{'Key': 'Owner','Value': Owner},{'Key': 'Infra_Owner','Value': Infra_Owner},{'Key': 'Business_Unit','Value': Business_Unit}]})\ns3_versioning=s3.put_bucket_versioning(Bucket=bucket_name,VersioningConfiguration={'Status': Versioning})\n","sub_path":"S3_Create.py","file_name":"S3_Create.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"299750679","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 8 14:40:39 2016\r\n\r\n@author: Florian Jehn\r\n\"\"\"\r\n# import argv from sys\r\nfrom sys import argv\r\n\r\n# read scriptname and the first argument from argv\r\nscript, filename = argv\r\n\r\n# open the file for reading purposes\r\ntxt = open(filename,\"r\")\r\n\r\n# print the filename\r\nprint(\"Here's your file %r: \" % filename)\r\n\r\n# print the whole file\r\nprint(txt.read())\r\n\r\n# prompt the user for the filename again\r\nprint(\"Type the filename again: \")\r\nfile_again = input(\"> \")\r\n\r\n# open the file once more\r\ntxt_again = open(file_again)\r\n\r\n# print the file once more\r\nprint(txt_again.read())\r\n\r\ntxt.close()\r\ntxt_again.close()","sub_path":"ex15.py","file_name":"ex15.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"127442097","text":"# -*- coding: UTF-8 -*-\nfrom AccessControl.SecurityManagement import getSecurityManager\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Five import BrowserView\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom cioppino.twothumbs import rate\nfrom plone import api\n\n\nclass AddonView(BrowserView):\n\n template = ViewPageTemplateFile('addonview.pt')\n\n def __call__(self):\n return self.template()\n\n\nclass SubmitAddon(BrowserView):\n\n def __call__(self):\n api.content.transition(self.context, 'submit')\n api.portal.show_message(\n message=\"Thank you for submitting '%s'\" % self.context.title,\n request=self.request,\n type='info')\n portal_url = api.portal.get().absolute_url()\n self.request.response.redirect(portal_url)\n\n\nclass AddonList(BrowserView):\n\n template = ViewPageTemplateFile('addonlist.pt')\n\n def items(self):\n results = []\n catalog = getToolByName(self.context, 'portal_catalog')\n brains = catalog.unrestrictedSearchResults(\n portal_type='addon',\n sort_on='sortable_title',\n review_state='pending',\n )\n for brain in brains:\n results.append(dict(\n title=brain.Title,\n state=brain.review_state,\n pypi_link=brain.pypi_link,\n ))\n return results\n\n def can_review(self):\n security = getSecurityManager()\n if security.checkPermission(\n 'paragon.site: Review Addon', self.context):\n return True\n\n\nclass AddonTable(BrowserView):\n \"\"\"\n \"\"\"\n\n template = ViewPageTemplateFile('addontable.pt')\n\n def items(self):\n results = []\n catalog = getToolByName(self.context, 'portal_catalog')\n brains = catalog(portal_type='addon')\n for brain in brains:\n obj = brain.getObject()\n tally = rate.getTally(obj)\n number_of_votes = tally['ups'] + tally['downs']\n if not number_of_votes:\n average_vote = '-'\n else:\n average_vote = (tally['ups'] - tally['downs']) \\\n / number_of_votes\n if average_vote > 0:\n average_vote = '+%s' % average_vote\n results.append(dict(\n title=brain.Title,\n url=brain.getURL(),\n pypi_link=brain.pypi_link,\n github_link=obj.github_link,\n state=brain.review_state,\n categories=', '.join(obj.categories),\n submitter=obj.name,\n tally=tally,\n number_of_votes=number_of_votes,\n average_vote=average_vote,\n ))\n return results\n","sub_path":"src/paragon/site/browser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"135234458","text":"from flask import Flask\nfrom flask import render_template\nfrom search import search\nfrom flask import *\nimport os\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef first():\n return render_template('FloodRelief.html')#predict.html\n@app.route('/req1', methods=['POST'])\ndef req1():\n inp = request.form['inp'];\n if(len(inp)>0):\n res=search(inp.strip())\n # out= json.dumps({'status':'OK','name':res[0],'address':res[1],'camp':res[2]});\n out=res.to_json()\n print(out)\n\n return out\n else:\n print(\"no inp\")\n return json.dumps({'status':'OK','name':'','address':'','camp':''});\n@app.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),\n 'favicon.ico', mimetype='image/vnd.microsoft.icon')\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"28378388","text":"\n\nimport sys\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom grakel.utils import graph_from_networkx\nfrom tqdm import tqdm\nfrom utils import load_file, preprocessing, get_vocab\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom grakel.kernels import Kernel\nfrom grakel.kernels import ShortestPath , PyramidMatch\nfrom grakel.kernels import WeisfeilerLehman, VertexHistogram\nfrom grakel.datasets import fetch_dataset\nfrom grakel import Graph\nfrom timeit import default_timer as timer\nfrom gpcharts import figure\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV\n\n\ndef spgk(sp_g1, sp_g2, norm1, norm2):\n \"\"\" \n Compute spgk kernel\n \"\"\"\n if norm1 == 0 or norm2==0:\n return 0\n else:\n kernel_value = 0\n for node1 in sp_g1:\n if node1 in sp_g2:\n kernel_value += 1\n for node2 in sp_g1[node1]:\n if node2 != node1 and node2 in sp_g2[node1]:\n kernel_value += (1.0/sp_g1[node1][node2]) * (1.0/sp_g2[node1][node2])\n\n kernel_value /= (norm1 * norm2)\n \n return kernel_value\n\ndef create_graphs_of_words1(docs, vocab, window_size):\n graphs = list()\n sizes = list()\n degs = list()\n print(vocab)\n for idx,doc in enumerate(docs):\n G = nx.Graph()\n for i in range(len(doc)):\n if doc[i] not in G.nodes():\n G.add_node(doc[i])\n G.nodes[doc[i]]['label'] = vocab[doc[i]]\n \n \n for i in range(len(doc)):\n for j in range(i+1, i+window_size):\n if j < len(doc):\n G.add_edge(doc[i], doc[j])\n \n graphs.append(G)\n \n return graphs\n\n\n\ndef create_graph_of_words(docs, voc, window_size):\n graphs = []\n for doc in docs:\n edges = {}\n unique_words = set()\n for i in range(len(doc)):\n unique_words.add(doc[i])\n for j in range(i+1, i+window_size):\n if j < len(doc):\n unique_words.add(doc[j])\n edge_tuple1 = (doc[i], doc[j])\n if edge_tuple1 in edges:\n edges[edge_tuple1] += 1\n else:\n edges[edge_tuple1] = 1\n node_labels = {word:voc[word] for word in unique_words}\n g = Graph(edges, node_labels=node_labels)\n graphs.append(g)\n\n return graphs\n\n\ndef main():\n \"\"\" \n Main function\n \"\"\"\n if len(sys.argv) != 5:\n print('Wrong number of arguments!!! Run as follows:')\n print('spgk.py ')\n else:\n filename_pos = sys.argv[1]\n filename_neg = sys.argv[2]\n window_size = int(sys.argv[3])\n depth = int(sys.argv[4])\n docs_pos = load_file(filename_pos)\n docs_pos = preprocessing(docs_pos)\n labels_pos = []\n for i in range(len(docs_pos)):\n labels_pos.append(1)\n\n docs_neg = load_file(filename_neg)\n docs_neg = preprocessing(docs_neg)\n labels_neg = []\n for i in range(len(docs_neg)):\n labels_neg.append(0)\n\n docs = docs_pos\n docs.extend(docs_neg)\n labels = labels_pos\n labels.extend(labels_neg)\n labels = np.array(labels)\n train_data, test_data, y_train, y_test = train_test_split(docs, labels, test_size=0.33, random_state=42)\n vocab = get_vocab(train_data,test_data)\n print(\"Vocabulary Size: \", len(vocab))\n \n \n \n # Create graph-of-words representations\n G_train = create_graph_of_words(train_data, vocab, window_size) \n G_test = create_graph_of_words(test_data, vocab, window_size)\n \n # Values of C parameter of SVM\n C_grid = (10. ** np.arange(-4,6,1) / len(G_train)).tolist()\n\n # Creates pipeline\n estimator = make_pipeline(\n ShortestPath(normalize=True),\n GridSearchCV(SVC(kernel='precomputed'), dict(C=C_grid),\n scoring='accuracy', cv=10))\n\n # Performs cross-validation and computes accuracy\n n_folds = 10\n acc = accuracy_score(G_test, cross_val_predict(estimator, G_train, G_test, cv=n_folds))\n print(\"Accuracy:\", str(round(acc*100, 2)) + \"%\") \n \n\n \n\nif __name__ == \"__main__\":\n main()","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"87545900","text":"from django.conf.urls import include, url, patterns\nfrom django.contrib import admin\n\nfrom Hypearave import settings\nfrom blog.views import PostListView, PostDetailView\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^search/', include('haystack.urls')),\n\n url(r'^channel/(?P\\d+)/$', PostListView.as_view(), name='channel'),\n url(r'^post/(?P\\d+)/$', PostDetailView.as_view(), name='post'),\n]\n\nif settings.DEBUG:\n # static files (social, css, javascript, etc.)\n urlpatterns += patterns('',\n (r'^media/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT})\n )\n","sub_path":"Hypearave/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"160919561","text":"import socket\nfrom .Frame import Frame\nfrom .Handshake import Handshake\n\n\nclass Server:\n \"\"\"\n A simple, single threaded, web socket server.\n \"\"\"\n def __init__(self, host='localhost', port=1337):\n self._handshake = Handshake()\n self._frame = Frame()\n\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self._socket.bind((host, port))\n\n self._on_message_handler = None\n self._on_close_handler = None\n self._running = False\n self._conn = None\n self._address = None\n\n self._received_payload = ''\n\n def start(self):\n \"\"\"\n Starts the server,\n \"\"\"\n print('Start')\n self._socket.listen(1)\n self._conn, self._address = self._socket.accept()\n self._running = True\n\n data = self._conn.recv(1024)\n self._conn.sendall(self._handshake.perform(data).encode(\"utf-8\"))\n\n while self._running:\n header = self._conn.recv(24) # Max web socket header length\n\n if len(data) > 0:\n self._frame = Frame()\n\n try:\n self._frame.parse(header)\n except IndexError:\n self._running = False\n continue\n\n if self._frame.terminate:\n self._running = False\n continue\n\n data = bytearray()\n data.extend(header)\n offset = self._frame.get_payload_offset()\n data.extend(self._conn.recv(offset))\n\n if self._frame.utf8:\n request = self._frame.get_payload(data).decode(\"utf-8\")\n self._received_payload += request.lstrip('\\x00')\n\n if self._frame.utf8 and self._frame.fin:\n self._on_message_handler.on_message(self._received_payload)\n self._received_payload = ''\n\n print('Stop')\n self.stop()\n\n def send_message(self, txt):\n \"\"\"\n Sends a message if the server is in running state.\n \"\"\"\n if not self._running:\n return\n\n self._frame = Frame()\n raw_data = self._frame.create(txt)\n self._conn.send(raw_data)\n\n def stop(self):\n \"\"\"\n Stops the server by sending the fin package to the client and closing the socket.\n \"\"\"\n self._running = False\n try:\n self._conn.send(self._frame.close())\n except BrokenPipeError:\n print('Ignored BrokenPipeError')\n\n self._conn.close()\n if self._on_close_handler:\n print('Triggering on_close')\n self._on_close_handler.on_close()\n\n def on_message(self, handler):\n \"\"\"\n Sets the on message handler.\n \"\"\"\n print('Setting on message handler')\n self._on_message_handler = handler\n self._on_message_handler.set_web_socket_server(self)\n\n def on_close(self, handler):\n \"\"\"\n Sets the on connection closed handler.\n \"\"\"\n print('Setting on close handler')\n self._on_close_handler = handler\n self._on_close_handler.set_web_socket_server(self)","sub_path":"SublimeText3Plugin/WebSocket/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"555543567","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.init import kaiming_uniform\nfrom Loss import MultilabelCrossEntropyLoss\nimport torchvision.models as models\n\nclass MemoryFlowNet(nn.Module):\n\n def __init__(self, opt):\n super(MemoryFlowNet, self).__init__()\n\n self.conv1_1 = nn.Conv2d(3, 64, 3, 1, 1)\n self.bn1_1 = nn.BatchNorm2d(64)\n self.relu1_1 = nn.ReLU()\n self.conv1_2 = nn.Conv2d(64, 64, 3, 1, 1)\n self.bn1_2 = nn.BatchNorm2d(64)\n self.relu1_2 = nn.ReLU()\n self.pool1 = nn.MaxPool2d(2,2)\n # self.conv1_memory = nn.Conv2d(32*5, 32, 3, 1, 1)\n\n self.conv2_1 = nn.Conv2d(64, 128, 3, 1, 1)\n self.bn2_1 = nn.BatchNorm2d(128)\n self.relu2_1 = nn.ReLU()\n self.conv2_2 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn2_2 = nn.BatchNorm2d(128)\n self.relu2_2 = nn.ReLU()\n self.pool2 = nn.MaxPool2d(2,2)\n # self.conv2_memory = nn.Conv2d(64*5, 64, 3, 1, 1)\n\n self.conv3_1 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn3_1 = nn.BatchNorm2d(128)\n self.relu3_1 = nn.ReLU()\n self.conv3_2 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn3_2 = nn.BatchNorm2d(128)\n self.relu3_2 = nn.ReLU()\n self.conv3_3 = nn.Conv2d(128, 128, 3, 1, 1)\n self.bn3_3 = nn.BatchNorm2d(128)\n self.relu3_3 = nn.ReLU()\n self.pool3 = nn.MaxPool2d(2,2)\n self.conv3_memory = nn.Conv2d(128*5, 128, 3, 1, 1)\n self.bn3_memory = nn.BatchNorm2d(128)\n self.relu3_memory = nn.ReLU()\n\n self.conv4_1 = nn.Conv2d(256, 256, 3, 1, 1)\n self.bn4_1 = nn.BatchNorm2d(256)\n self.relu4_1 = nn.ReLU()\n self.conv4_2 = nn.Conv2d(256, 256, 3, 1, 1)\n self.bn4_2 = nn.BatchNorm2d(256)\n self.relu4_2 = nn.ReLU()\n self.conv4_3 = nn.Conv2d(256, 256, 3, 1, 1)\n self.bn4_3 = nn.BatchNorm2d(256)\n self.relu4_3 = nn.ReLU()\n self.pool4 = nn.MaxPool2d(2, 2)\n self.conv4_memory = nn.Conv2d(256 * 5, 256, 3, 1, 1)\n self.bn4_memory = nn.BatchNorm2d(256)\n self.relu4_memory = nn.ReLU()\n\n self.conv5_1 = nn.Conv2d(512, 512, 3, 1, 1)\n self.bn5_1 = nn.BatchNorm2d(512)\n self.relu5_1 = nn.ReLU()\n self.conv5_2 = nn.Conv2d(512, 512, 3, 1, 1)\n self.bn5_2 = nn.BatchNorm2d(512)\n self.relu5_2 = nn.ReLU()\n self.conv5_3 = nn.Conv2d(512, 512, 3, 1, 1)\n self.bn5_3 = nn.BatchNorm2d(512)\n self.relu5_3 = nn.ReLU()\n self.pool5 = nn.MaxPool2d(2, 2)\n self.conv5_memory = nn.Conv2d(512 * 5, 512, 3, 1, 1)\n self.bn5_memory = nn.BatchNorm2d(512)\n self.relu5_memory = nn.ReLU()\n\n self.fc1 = nn.Linear(1024*7*7, 4096)\n self.relu_fc1 = nn.ReLU()\n self.drop1 = nn.Dropout(p=0.5)\n self.fc2 = nn.Linear(4096, 4096)\n self.relu_fc2 = nn.ReLU()\n self.drop2 = nn.Dropout(p=0.5)\n self.fc3 = nn.Linear(4096, 157)\n\n self.memory = {'conv1': [torch.zeros(1, 32, 112, 112).cuda() for _ in range(5)],\n 'conv2': [torch.zeros(1, 64, 56, 56).cuda() for _ in range(5)],\n 'conv3': [torch.zeros(1, 128, 28, 28).cuda() for _ in range(5)],\n 'conv4': [torch.zeros(1, 256, 14, 14).cuda() for _ in range(5)],\n 'conv5': [torch.zeros(1, 512, 7, 7).cuda() for _ in range(5)]}\n\n self.initialize_weights()\n\n def forward(self, inputs):\n batch_size = inputs.size(0)\n seq_len = inputs.size(1)\n self.init_memory(batch_size)\n\n for i in range(seq_len):\n out = self.relu1_1(self.bn1_1(self.conv1_1(inputs[:, i])))\n out = self.relu1_2(self.bn1_2(self.conv1_2(out)))\n out = self.pool1(out)\n # memory_out = self.conv1_memory(Variable(torch.cat(self.memory['conv1'], 1)).cuda())\n # self.memory['conv1'].pop(0)\n # self.memory['conv1'].append(out.detach().data)\n # out = torch.cat([out, memory_out], 1)\n\n out = self.relu2_1(self.bn2_1(self.conv2_1(out)))\n out = self.relu2_2(self.bn2_2(self.conv2_2(out)))\n out = self.pool2(out)\n # memory_out = self.conv2_memory(Variable(torch.cat(self.memory['conv2'], 1)).cuda())\n # self.memory['conv2'].pop(0)\n # self.memory['conv2'].append(out.detach().data)\n # out = torch.cat([out, memory_out], 1)\n\n out = self.relu3_1(self.bn3_1(self.conv3_1(out)))\n out = self.relu3_2(self.bn3_2(self.conv3_2(out)))\n out = self.relu3_3(self.bn3_3(self.conv3_3(out)))\n out = self.pool3(out)\n memory = torch.cat(self.memory['conv3'], 1)\n memory_out = self.conv3_memory(Variable(memory).cuda())\n memory_out = self.relu3_memory(self.bn3_memory(memory_out))\n self.memory['conv3'].pop(0)\n self.memory['conv3'].append(out.data)\n out = torch.cat([out, memory_out], 1)\n\n out = self.relu4_1(self.bn4_1(self.conv4_1(out)))\n out = self.relu4_2(self.bn4_2(self.conv4_2(out)))\n out = self.relu4_3(self.bn4_3(self.conv4_3(out)))\n out = self.pool4(out)\n memory = torch.cat(self.memory['conv4'], 1)\n memory_out = self.conv4_memory(Variable(memory).cuda())\n memory_out = self.relu4_memory(self.bn4_memory(memory_out))\n self.memory['conv4'].pop(0)\n self.memory['conv4'].append(out.data)\n out = torch.cat([out, memory_out], 1)\n\n out = self.relu5_1(self.bn5_1(self.conv5_1(out)))\n out = self.relu5_2(self.bn5_2(self.conv5_2(out)))\n out = self.relu5_3(self.bn5_3(self.conv5_3(out)))\n out = self.pool5(out)\n memory = torch.cat(self.memory['conv5'], 1)\n memory_out = self.conv5_memory(Variable(memory).cuda())\n memory_out = self.relu5_memory(self.bn5_memory(memory_out))\n self.memory['conv5'].pop(0)\n self.memory['conv5'].append(out.data)\n out = torch.cat([out, memory_out], 1)\n\n out = out.view(-1, 1024*7*7)\n out = self.drop1(self.relu_fc1(self.fc1(out)))\n out = self.drop2(self.relu_fc2(self.fc2(out)))\n out = self.fc3(out)\n\n return out\n\n def init_memory(self, batch_size):\n self.memory = {'conv1': [torch.zeros(batch_size, 32, 112, 112).cuda() for _ in range(5)],\n 'conv2': [torch.zeros(batch_size, 64, 56, 56).cuda() for _ in range(5)],\n 'conv3': [torch.zeros(batch_size, 128, 28, 28).cuda() for _ in range(5)],\n 'conv4': [torch.zeros(batch_size, 256, 14, 14).cuda() for _ in range(5)],\n 'conv5': [torch.zeros(batch_size, 512, 7, 7).cuda() for _ in range(5)]}\n\n def _init_layer(self, layer, name):\n # for layer in layers:\n if str(layer).startswith(name):\n kaiming_uniform(layer.weight.data)\n if layer.bias is not None:\n layer.bias.data.zero_()\n\n def initialize_weights(self):\n self._init_layer(self.conv1_1, 'Conv')\n self._init_layer(self.conv1_2, 'Conv')\n # self._init_layer(self.conv1_memory, 'Conv')\n self._init_layer(self.conv2_1, 'Conv')\n self._init_layer(self.conv2_2, 'Conv')\n # self._init_layer(self.conv2_memory, 'Conv')\n self._init_layer(self.conv3_1, 'Conv')\n self._init_layer(self.conv3_2, 'Conv')\n self._init_layer(self.conv3_3, 'Conv')\n self._init_layer(self.conv3_memory, 'Conv')\n self._init_layer(self.conv4_1, 'Conv')\n self._init_layer(self.conv4_2, 'Conv')\n self._init_layer(self.conv4_3, 'Conv')\n self._init_layer(self.conv4_memory, 'Conv')\n self._init_layer(self.conv5_1, 'Conv')\n self._init_layer(self.conv5_2, 'Conv')\n self._init_layer(self.conv5_3, 'Conv')\n self._init_layer(self.conv5_memory, 'Conv')\n self._init_layer(self.fc1, 'Linear')\n self._init_layer(self.fc2, 'Linear')\n self._init_layer(self.fc3, 'Linear')\n\nif __name__ == \"__main__\":\n torch.cuda.set_device(1)\n\n model = models.vgg16_bn(pretrained=True)\n net = MemoryFlowNet({}).cuda()\n a = model.state_dict()\n for param in model.state_dict():\n print(param)\n inputs = torch.FloatTensor(16, 3, 224, 224)\n mask = torch.randn(16, 157)\n targets = mask.ge(0.5)\n res = net(Variable(inputs).cuda())\n crit = MultilabelCrossEntropyLoss().cuda()\n\n loss = crit(res, Variable(targets.float()).cuda())\n\n\n print(res)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"529493565","text":"import serial\nfrom . import constants\ndef connection(ipaddress,port):\n\tserport = serial.serial_for_url(\"socket://\"+ipaddress+\":\"+port+\"/logging=debug\")\n\tserport.close()\n\t#serport.port = constants.COM_PORT\n\tserport.baudrate = constants.COM_BAUD\n\tserport.bytesize = constants.COM_SIZE\n\tserport.parity = constants.COM_PARITY\n\tserport.stopbits = constants.COM_STOP\n\tserport.timeout = constants.COM_TIMEOUT\n\ttry:\n\t serport.open()\n\texcept serial.SerialException as e:\n\t s= \"%s : Could not open serial port %s: %s\\n\" % (localtime, serport.portstr, e)\n\t sys.stderr.write(s)\n\t problem += 1\n\tserport.close()\n\treturn serport\n","sub_path":"build/lib/heatmiserV3/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"73147847","text":"import threading\nimport socket\nimport json\nimport numpy as np\nimport utils\nimport requests\nimport base64\nimport hashlib\nimport struct\n\n'''\nPython处理前端javascript发来的数据解码和编码参考以下内容,针对其中BUG有修改\nhttps://blog.csdn.net/ice110956/article/details/34118203\n'''\n#支持的API类型,如果token不在list中则认为无效\nAPI_Surport_List = ['SR']\nues_tf_serving = False\ntf_serving_url = 'http://localhost:8501/v1/models/{}:predict'\nif not ues_tf_serving:\n\tyysb = utils.SpeechRecognition(test_flag=False)\n\n\ndef SR_recognize(wavs,pre_type):\n hanzi =''\n am_url = tf_serving_url.format('am')\n lm_url = tf_serving_url.format('lm')\n if ues_tf_serving:\n x,_,_ = utils.get_wav_Feature(wavsignal=wavs)\n try:\n receipt = requests.post(am_url,data='{\"instances\":%s}' % x.tolist()).json()['predictions'][0]\n receipt = np.array([receipt],dtype=np.float32)\n except:\n return _,'声学模型调用异常'\n _, pinyin = utils.decode_ctc(receipt, utils.pny_vocab)\n pinyin = [[utils.pny_vocab.index(p) for p in ' '.join(pinyin).strip('\\n').split(' ')]]\n if pre_type == 'H':\n #curl -d '{\"instances\": [[420,58]]}' -X POST http://localhost:8501/v1/models/lm:predict\n try:\n hanzi = requests.post(lm_url,data='{\"instances\": %s}' % pinyin).json()['predictions'][0]\n except:\n return _,'语言模型调用异常'\n hanzi = ''.join(utils.han_vocab[idx] for idx in hanzi)\n else:\n if pre_type == 'H':\n pinyin,hanzi = yysb.predict(wavs)\n else:\n pinyin = yysb.predict(wavs,only_pinyin = True)\n return pinyin,hanzi\n\n\ndef encode_data(data):\n data = data.encode('utf-8')\n token = b\"\\x81\"\n length = len(data)\n if length < 126:\n token += struct.pack(\"B\", length)\n elif length <= 0xFFFF:\n token += struct.pack(\"!BH\", 126, length)\n else:\n token += struct.pack(\"!BQ\", 127, length)\n #struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式。\n data = token + data\n return data\n\n\ndef tcplink(sock, addr):\n print('Accept new connection from %s:%s...' % addr)\n js_flag = False\n js_saver = b''#防止数据过长时单次接收不全\n while True:\n all_data = sock.recv(524288)\n if not all_data:\n break\n js_saver += all_data\n all_data = js_saver#all_data从js_saver处获取目前为止的全部数据\n try:\n datas = all_data.decode('utf-8')\n except:#处理前端js发来的websocket数据,还要进行解码处理\n js_flag = True\n code_len = all_data[1] & 127\n if code_len == 126:\n masks = all_data[4:8]\n all_data = all_data[8:]\n elif code_len == 127:\n masks = all_data[10:14]\n all_data = all_data[14:]\n else:\n masks = all_data[2:6]\n all_data = all_data[6:]\n datas = \"\"\n for i,d in enumerate(all_data):\n datas += chr(d ^ masks[i % 4])\n try:\n if datas.find('token') < 0 or datas.find('pre_type') < 0:\n continue\n datas = json.loads(datas)\n js_saver = b''\n except BaseException as e:\n print(e)\n continue\n token = datas['token']\n pre_type = datas['pre_type']\n receipt_data = list(datas['data'])\n \n if(token not in API_Surport_List):\n sock.send(b'token unsupported')\n\t\t\n if len(receipt_data)>0:\n if token == 'SR':\n wavs = np.array([int(w) for w in receipt_data])\n _,r = SR_recognize(wavs, pre_type)\n else:\n pass\n else:\n r = ''\n \n if js_flag:\n r = encode_data(r)\n else:\n r = r.encode('utf-8')\n sock.send(r)\n sock.close()\n print('Connection from %s:%s closed.\\n' % addr)\n\n\nif __name__ == \"__main__\":\n IPs = socket.gethostbyname_ex(socket.gethostname())[-1]\n # family=AF_INET - IPv4地址\n # family=AF_INET6 - IPv6地址\n # type=SOCK_STREAM - TCP套接字\n # type=SOCK_DGRAM - UDP套接字\n # type=SOCK_RAW - 原始套接字 \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 监听端口:\n s.bind(('172.16.100.29', 9999))\n s.listen(255)# 参数255可以理解为连接队列的大小\n while True:\n # 接受一个新连接:\n # accept方法是一个阻塞方法如果没有客户端连接到服务器代码不会向下执行\n client, addr = s.accept()\n data = str(client.recv(1024))\n header_dict = {}\n header, _ = data.split(r'\\r\\n\\r\\n', 1)\n for line in header.split(r'\\r\\n')[1:]:\n key, val = line.split(': ', 1)\n header_dict[key] = val\n\n if 'Sec-WebSocket-Key' not in header_dict:\n print('This socket is not websocket, client close.')\n client.close()\n continue\n\n magic_key = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n sec_key = header_dict['Sec-WebSocket-Key'] + magic_key\n key = base64.b64encode(hashlib.sha1(bytes(sec_key, encoding='utf-8')).digest())\n key_str = str(key)[2:30]\n\n response = 'HTTP/1.1 101 Switching Protocols\\r\\n' \\\n 'Connection: Upgrade\\r\\n' \\\n 'Upgrade: websocket\\r\\n' \\\n 'Sec-WebSocket-Accept: {0}\\r\\n' \\\n 'WebSocket-Protocol: chat\\r\\n\\r\\n'.format(key_str)\n client.send(bytes(response, encoding='utf-8'))#针对普通js建立的websocket一定要回一个建立连接\n # 创建新线程来处理TCP连接:\n t = threading.Thread(target=tcplink, args=(client, addr))\n t.start()\n","sub_path":"AboutDL/语音识别ASRT/service_socket.py","file_name":"service_socket.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"259844400","text":"# Задача 5. Вариант 11.\n#Напишите программу, которая бы при запуске случайным образом отображала имя одного из девяти оленей Санта Клауса. \n \n# Kurchatov N. V.\n# 11.04.2016\n\nimport random\nx=random.randint(1,9)\nif x==1:\n\tname=\"Дэшер\"\nelif x==2:\n\tname = \"Дэнсер\"\nelif x==3:\n\tname = \"Прэнсер\"\nelif x==4:\n\tname = \"Виксен\"\nelif x==5:\n\tname = \"Комет\"\nelif x==6:\n\tname = \"Кь��пид\"\nelif x==7:\n\tname = \"Дондер\"\nelif x==8:\n\tname = \"Блитцен\"\nelif x==9:\n\tname = \"Рудольф\"\t\n\t\nprint (\"Имя одного из оленей Санты - \"+name)\ninput(\"Нажмите Enter для выхода\")","sub_path":"INBa/2015/KURCHATOV_N_V/z5_11.py","file_name":"z5_11.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"441813869","text":"import os\n\nimport numpy as np\nfrom preprocessing.cropper import Cropper\n\n\n\nclass TrainTestSampleGen(object):\n\n def __init__(self, ucf_path, hmdb_path):\n if ucf_path != '':\n self.train_data_label, self.test_data_label = self.ucf_read_train_test_split(ucf_path)\n if hmdb_path != '':\n self.train_data_label, self.test_data_label = self.hmdb_read_train_test_split(hmdb_path)\n\n def ucf_read_train_test_split(self, path):\n \"\"\"\n Read the name of train and test samples from the txt files which are stored under path, split them into train,\n test lists.\n :param path: The path of folder stores the train test split txt files\n :return: two lists of dict, train and test which contain the video name and labels for train and test.\n \"\"\"\n # get the test train split txt file\n train = []\n test = []\n for (dirpath, dirnames, filenames) in os.walk(path):\n train += [os.path.join(path, file) for file in filenames if file.startswith('trainlist')]\n test += [os.path.join(path, file) for file in filenames if file.startswith('testlist')]\n train.sort()\n test.sort()\n\n # read test train data name and label from the txt file\n train_data_labels = []\n test_data_labels = []\n for tra, test in zip(train, test):\n with open(tra) as f:\n names_labels = f.readlines()\n data = [line.split(' ')[0].split('/')[-1].split('.')[0] for line in names_labels]\n label = [line.split(' ')[0].split('/')[0] for line in names_labels]\n train_data_labels.append({'data': data, 'label': label})\n with open(test) as f:\n names_labels = f.readlines()\n data = [line.split('/')[-1].split('.')[0] for line in names_labels]\n label = [line.split('/')[0] for line in names_labels]\n test_data_labels.append({'data': data, 'label': label})\n return train_data_labels, test_data_labels\n\n def train_test_split(self, path, dataset, idx, crop=False):\n \"\"\"\n Read the data that names are given in self.ucf_train_data_labels and self.ucf_test_data_labels.\n Save the data and label into a dict. Each time this function is called, only read one train or test split.\n :param path: feature store path\n :param dataset: ucf or hmdb\n :return: the dicts with the format {'data': data, 'label': labels}\n \"\"\"\n if dataset == 'ucf':\n train_data_label = self.ucf_train_data_label[idx].copy()\n test_data_label = self.ucf_test_data_label[idx].copy()\n else:\n train_data_label = self.hmdb_train_data_label[idx].copy()\n test_data_label = self.hmdb_test_data_label[idx].copy()\n\n if crop == True:\n train_data = [Cropper(np.load(os.path.join(path, name + '.npy')), (224, 224)).crop_image() for name in\n train_data_label['data']]\n test_data = [Cropper(np.load(os.path.join(path, name + '.npy')), (224, 224)).crop_image() for name in\n test_data_label['data']]\n else:\n train_data = [np.load(os.path.join(path, name + '.npy')) for name in train_data_label['data']]\n test_data = [np.load(os.path.join(path, name + '.npy')) for name in test_data_label['data']]\n\n train_data_label['data'] = train_data\n test_data_label['data'] = test_data\n return train_data_label, test_data_label\n\n def hmdb_read_train_test_split(self, path):\n \"\"\"\n Read the name of train and test samples from the txt files which are stored under path, split them into train,\n test lists.\n :param path: The path of folder stores the train test split txt files\n :return: two lists of dict, train and test which contain the video name and labels for train and test.\n \"\"\"\n # read file names according to the split number from 1 to 3\n action_splits = []\n for (dirpath, dirnames, filenames) in os.walk(path):\n for i in range(1, 4, 1):\n action_splits.append(\n sorted([os.path.join(path, f) for f in filenames if f.split('.')[0].endswith(str(i))]))\n\n # fetch the data and labels for all 3 splits\n train_data_labels = []\n test_data_labels = []\n for s in action_splits:\n train_data = []\n train_label = []\n test_data = []\n test_label = []\n for a in s:\n with open(a) as f:\n name_labels = f.readlines()\n train = [line.split(' ')[0].split('.')[0] for line in name_labels if\n line.rstrip().split(' ')[-1] == '1']\n train_data += train\n train_label += [a.split('/')[-1][:a.split('/')[-1].index('test')-1] for i in range(len(train))]\n test = [line.split(' ')[0].split('.')[0] for line in name_labels if\n line.rstrip().split(' ')[-1] == '2']\n test_data += test\n test_label += [a.split('/')[-1][:a.split('/')[-1].index('test')-1] for i in range(len(test))]\n train_data_labels.append({'data': train_data, 'label': np.array(train_label)})\n test_data_labels.append({'data': test_data, 'label': np.array(test_label)})\n return train_data_labels, test_data_labels\n\nif __name__ == '__main__':\n ucf_path = \"/home/boy2/UCF101/ucf101_dataset/features/testTrainSplits\"\n hmdb_path = \"/home/boy2/UCF101/hmdb51_dataset/features/testTrainSplits\"\n tts = TrainTestSampleGen(ucf_path, hmdb_path)\n tts.hmdb_read_train_test_split(hmdb_path)\n","sub_path":"src/trainTestSamplesGen.py","file_name":"trainTestSamplesGen.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"409279987","text":"#!/usr/bin/env python3\r\n\r\nimport os\r\n\r\nreplacechars = {\r\n '_':'-'\r\n}\r\n\r\nfilelist = os.listdir()\r\nfor file in filelist:\r\n if os.path.isdir(file):\r\n continue\r\n a = list(file)\r\n for i,val in enumerate(a):\r\n if replacechars.get(val):\r\n a[i]=replacechars[val]\r\n b = ''.join(a)\r\n if file!=b:\r\n os.rename(file,b)\r\n print(b)","sub_path":"others/filereplacechar.py","file_name":"filereplacechar.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"114113470","text":"import pyaudio\nimport numpy as np\nimport wave\nimport matplotlib.pyplot as plt\n\np = pyaudio.PyAudio()\nfreqs=np.array([0])\np.get_default_input_device_info()\nstream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=2048)\nframes = []\nRECORD_SECONDS = 30\nnchunks = int(RECORD_SECONDS * 44100 / 2048)\nfor i in range(0, nchunks):\n try:\n data = stream.read(2048)\n except IOError as ex: #error que ens dona (Input Overflowed)\n if ex[1] != pyaudio.paInputOverflowed:\n raise\n data = '\\x00' * 2048\n frames.append(data)\n swidth = 2\n chunk = 2048\n window = np.blackman(chunk)\n indata = np.array(wave.struct.unpack(\"%dh\"%(len(data)/swidth),\\\n data))*window\n # S'agafen els valors de la FFT i s'eleven al quadrat\n fftData=abs(np.fft.rfft(indata))**2\n # es troba el màxim\n which = fftData[1:].argmax() + 1\n # s'utilitza la interpolació quadràtica al màxim\n if which != len(fftData)-1:\n y0,y1,y2 = np.log(fftData[which-1:which+2:])\n x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)\n # es troba la freqüència\n thefreq = (which+x1)*44100/chunk\n else:\n thefreq = which*44100/chunk\n if 100<=thefreq<=10000:\n #print ('La freqüència és de %f Hz.' % (thefreq))\n print (thefreq)\n #plt.plot(i,thefreq,\"ro\")\n freqs=np.insert(freqs, -1, float(thefreq))\n freqs_t=np.insert(freqs, -1, (i, float(thefreq)))\n a, b = freqs[-1], freqs[-2]\n freqs[-1], freqs[-2] = b, a\n#plt.show()\n","sub_path":"Antics/direct_red.py","file_name":"direct_red.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"4001623","text":"import pandas as pd\nfrom bokeh.charts import Bar, output_file, show\nfrom bokeh.layouts import column\nfrom bokeh.models import (HoverTool, BoxSelectTool, BoxZoomTool, ResetTool,\n PanTool, WheelZoomTool, ResizeTool)\n\n\nclass AlignViz2(object):\n\n def alignment_stats(self, input_path_file, output_path_file_csv,\n output_path_file_html):\n df = pd.read_json(input_path_file, orient='index')\n df.to_csv(output_path_file_csv + '.csv',\n index=True, sep='\\t')\n\n samples = []\n alignment_length = []\n alignment_freq = []\n for index, row in df.iterrows():\n for key, value in row['stats_per_reference'].items():\n samples.extend([\n index + '(' + key + ')'] * int(self.nr_items_align(value)))\n for k, v in value.items():\n if k == 'alignment_length_and_freqs':\n for keys, values in v.items():\n alignment_length.extend([float(keys)])\n alignment_freq.extend([values])\n\n data1 = {}\n data1['samples'] = samples\n data1['aligned read length'] = alignment_length\n data1['frequency'] = alignment_freq\n\n bar1 = Bar(\n data1, values='frequency', label='aligned read length',\n stack='samples', agg='sum',\n title=\"Alignment read length and frequency\",\n legend='top_left', width=1200, bar_width=1.0,\n palette=['Blue', 'Aqua', 'SeaGreen', 'SpringGreen', 'Brown',\n 'Peru', 'Purple', 'Violet'],\n tools=[\n HoverTool(tooltips=[(\n \"Read length\", \"@x\"), (\"Frequency\", \"@y\")]),\n PanTool(), BoxSelectTool(), BoxZoomTool(),\n WheelZoomTool(), ResizeTool(), ResetTool()])\n\n output_file(output_path_file_html + '.html')\n show(bar1)\n \n def nr_items_align(self, value):\n item_nr_align = []\n for k, v in value.items():\n if k == 'alignment_length_and_freqs':\n for keys, values in v.items():\n item_nr_align.extend([keys])\n return(len(item_nr_align))\n\n def process_stats(self, input_path_file, output_path_file_csv,\n output_path_file_html):\n df = pd.read_json(input_path_file, orient='index')\n df.to_csv(output_path_file_csv + '.csv', index=True, sep='\\t')\n\n # plotting read processing(poly/single A removed or unmodified)\n conditions = []\n for row in df.iterrows():\n conditions.extend([\n 'poly(A) removed', 'single(A) removed', 'unmodified'])\n\n samples1 = []\n for index, row in df.iterrows():\n samples1.extend([index] * 3)\n\n read_nr = []\n for index, row in df.iterrows():\n read_nr.extend([\n row['polya_removed'], row['single_a_removed'],\n row['unmodified']])\n\n data1 = {}\n data1['condition'] = conditions\n data1['sample'] = samples1\n data1['Nr. of reads'] = read_nr\n\n bar1 = Bar(\n data1, values='Nr. of reads', label='sample',\n stack='condition',\n agg='sum', title=\"Input read types\", legend='top_right',\n palette=['darkseagreen', 'salmon', 'darkslateblue'],\n tools=[\n HoverTool(tooltips=[(\n \"Sample\", \"@x\"), (\"Nr of reads\", \"@y\")]),\n PanTool(), BoxSelectTool(), BoxZoomTool(),\n WheelZoomTool(), ResizeTool(), ResetTool()])\n\n samples2 = []\n read_length = []\n frequency = []\n for index, row in df.iterrows():\n for key, value in row[\n 'read_length_after_processing_and_freq'].items():\n samples2.extend([index] * int(self.nr_items_pro(key)))\n read_length.extend([float(key)])\n frequency.extend([value])\n\n data2 = {}\n data2['samples'] = samples2\n data2['read length'] = read_length\n data2['frequency'] = frequency\n\n bar2 = Bar(\n data2, values='frequency', label='read length',\n stack='samples', agg='sum',\n title=\"Input read length and frequency\",\n legend='top_left', palette=[\n 'darkseagreen', 'salmon', 'darkslateblue', 'olive'],\n width=1200, bar_width=1.0,\n tools=[\n HoverTool(tooltips=[(\n \"Read length\", \"@x\"), (\"Frequency\", \"@y\")]),\n PanTool(), BoxSelectTool(), BoxZoomTool(),\n WheelZoomTool(), ResizeTool(), ResetTool()])\n\n bar = column(bar1, bar2)\n output_file(output_path_file_html + '.html')\n show(bar)\n \n def nr_items_pro(self, key):\n item_nr_pro = []\n item_nr_pro.extend([key])\n return(len(item_nr_pro))\n \n\n","sub_path":"reademptionlib/vizalign2.py","file_name":"vizalign2.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"138620393","text":"\n# %%\nimport pymongo\nimport keyring\nimport pandas as pd\nimport requests\nimport pyocr\nfrom pdf2image import convert_from_path\nimport sys\nfrom pathlib import Path\n\n\n#%%\nclass MongoClient:\n def __init__(self):\n self.conn = pymongo.MongoClient(keyring.get_password('sentencias-db', 'default'))\n self.db = self.conn.sentencias\n self.collection = self.db.sentencia\n \n def query(self, query:dict = {}):\n ''' Regresa un dataframe a partir de una consulta de mongo.\n args:\n query: Diccionario con filtros de la consulta.\n returns:\n Dataframe de la consulta.\n '''\n docs = []\n cursor = self.collection.find(query)\n for doc in cursor:\n docs.append(doc)\n data = pd.DataFrame.from_dict(docs)\n return data\n\nclass Pdf2Text(MongoClient):\n def __init__(self, input_path = Path(), output_path = Path()):\n self.input_path = input_path\n self.output_path = pyocr.get_available_tools()\n tools = pyocr.get_available_tools()\n if len(tools) == 0:\n print(\"No OCR tool found\")\n sys.exit(1)\n self.tool = tools[0]\n self.lang = 'spa'\n\n def pdf2string(self, pdf_path):\n ''' Usando el path de un archivo pdf extraemos el texto mediante OCR de Tesseract.'''\n images = self.pdf2img(pdf_path) \n txt = ''\n for img in enumerate(images):\n txt += self.img2string(img)\n\n def img2string(self, img):\n ''' Usando una imagen de un pdf, regresa la cadena de strings contenida en la misma.'''\n txt = self.tool.image_to_string(img, lang=self.lang, builder=pyocr.builders.TextBuilder())\n return txt\n\n def pdf2img(self, pdf_path):\n ''' Convierte paginas de un pdf en imagenes.'''\n return convert_from_path(pdf_path)\n\n\n#%%\nif __name__ == '__main__':\n txts = []\n client = MongoClient()\n data = client.query()\n converter = Pdf2Text()\n temp_path = Path('temp.pdf')\n for pdf_link in data['pdf links']:\n response = requests.get(pdf_link)\n with open(temp_path, 'wb') as out:\n out.write(response.content)\n txt = converter.pdf2string(temp_path)\n txts.append(txt)\n\n\n\n\n\n","sub_path":"lib/MongoClient.py","file_name":"MongoClient.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"145778373","text":"import cv2\nimport numpy as np\nimport imutils\n# import pytesseract\nfrom collections import Counter\nfrom pandas import DataFrame as df\nPATH_CROPPED = './cropped/'\nPATH_OTHERS = 'D:/python/others/'\nPATH = PATH_OTHERS\n'''水平投影'''\n\n\ndef getHProjection(image):\n hProjection = np.zeros(image.shape, np.uint8)\n print('------1-------')\n # 图片高与宽\n (h, w) = image.shape\n print(h, w)\n # 长度与图像高度一致的数组\n h_ = [0] * h\n # 循环统计每一行白色像素的个数\n for y in range(h):\n for x in range(w):\n if image[y, x] == 255:\n h_[y] += 1\n\n # 绘制水平投影图像\n for y in range(h):\n for x in range(h_[y]):\n hProjection[y, x] = 255\n\n\n # cv2.imshow('hProjection2', hProjection)\n # cv2.waitKey(0)\n\n return h_\n\n\ndef getVProjection(image):\n vProjection = np.zeros(image.shape, np.uint8)\n (h, w) = image.shape\n\n w_ = [0] * w\n\n for x in range(w):\n for y in range(h):\n if image[y, x] == 255:\n w_[x] += 1\n\n for x in range(w):\n for y in range(h - w_[x], h):\n vProjection[y, x] = 255\n\n # cv2.imshow('vProjection', vProjection)\n cv2.waitKey(0)\n return w_\n\n\ndef fill_color(img, seedpoint):\n copyimg = img.copy()\n h, w = img.shape[:2]\n mask = np.zeros([h + 2, w + 2], np.uint8)\n mask[seedpoint[0]:seedpoint[2], seedpoint[1]:seedpoint[3]] = 0\n cv2.floodFill(copyimg, mask, (seedpoint[0] + 1, seedpoint[1] + 1), (0, 255, 255),\n flags=cv2.FLOODFILL_MASK_ONLY)\n # cv2.imshow('fill_color',copyimg)\n\n\ndef modify_position(w, threshold=6):\n t = get_threshold(w, threshold)\n w_counter = Counter(w)\n weight = []\n for i in t:\n \tweight.append(w_counter[i])\n\n m_mean = int(np.average(tuple(t), weights=weight))\n print(m_mean)\n # m_mean = sum(t)//len(t)\n m_max = max(t)\n w_ = []\n for item in w:\n if item < m_max and item > 0:\n w_.append(m_mean)\n # elif item < m_max:\n # w_.append(m_mean)\n else:\n \tw_.append(item)\n return w_, m_mean\n\n\ndef get_threshold(w, threshold=6):\n\tw_ = [0 if item < 2 else item for item in w]\n\tt = sorted(list(set(w_)))[1:threshold]\n\treturn t\n\n\ndef main(file):\n\torigineImage = cv2.imread(file)\n\tprint(file)\n\t# cv2.imshow('begin', origineImage)\n\torigineImage = imutils.resize(origineImage, width=1280)\n\t# 图片灰度化\n\timg = cv2.cvtColor(origineImage, cv2.COLOR_RGB2GRAY)\n # cv2.imshow('gray', img)\n # 二值化\n\tretval, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n\t# cv2.imshow('binary', img)\n\tcv2.waitKey(0)\n # img = cv2.GaussianBlur(img,(3,3),0)\n # img = cv2.blur(img,(3,3))\n # img = cv2.medianBlur(img,5)\n # img = cv2.bilateralFilter(img,9,75,75)\n # cv2.imshow('Gauss',img)\n \n\n # contours, hierarchy = cv2.findContours(img,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)\n # cv2.imshow('contours',img)\n # kernel = np.ones((3, 3), np.uint8)\n # img = cv2.erode(img, kernel)\n # cv2.imshow('eroimg',img)\n # for i in range(len(contours)):\n # \tcv2.drawContours(img,contours,i,(0,255,255),3)\n # \tcv2.fillPoly(img,[contours[i]],(255,255,0))\n # cv2.imshow('fill',img)\n # print(type(contours),contours)\n # print(file)\n\t(h, w) = img.shape\n\tPosition = []\n # 水平投影\n\tH = getHProjection(img)\n\t# print(H)\n\tstart = 0\n\tH_Start = []\n\tH_End = []\n # 根据水平投影获取垂直分割位置\n\tfor i in range(len(H)):\n\t if H[i] > 0 and start == 0:\n\t H_Start.append(i)\n\t start = 1\n\t if H[i] <= 0 and start == 1:\n\t H_End.append(i)\n\t start = 0\n # 分割行,分割之后再进行列分割列并保存分割位置\n\t# print(H_Start)\n\t# print(H_End)\n\tfor i in range(len(H_Start)):\n\t # 获取行图像\n\t cropImg = img[H_Start[i]:H_End[i], 0:w]\n\t # cv2.imshow('cropImg', cropImg)\n\t # 对行图像进行垂直投影\n\t W = getVProjection(cropImg)\n\t # print(W)\n\t threshold = 10\n\t W, mean = modify_position(W, threshold)\n\t # print(W)\n\t WStart = 0\n\t WEnd = 0\n\t W_Start = 0\n\t W_End = 0\n\t for j in range(len(W)):\n\t if W[j] > mean and WStart == 0:\n\t W_Start = j\n\t WStart = 1\n\t WEnd = 0\n\t if (j >= w-1 and WStart == 1) or (W[j] <=0 and WStart == 1):\n\t W_End = j\n\t WStart = 0\n\t WEnd = 1\n\t if WEnd == 1:\n\t Position.append([W_Start, H_Start[i], W_End, H_End[i]])\n\t WEnd = 0\n\n\t# new_Position = modify_position(Position)\n\t# print(Position)\n\tfor m in range(len(Position)):\n\t cv2.rectangle(origineImage, (Position[m][0], Position[m][1]),\n\t (Position[m][2], Position[m][3]), (0, 229, 238), 1)\n\t # fill_color(origineImage,Position[m])\n\n\tcv2.imshow('image', origineImage)\n\tcv2.waitKey(0)\n\treturn Position\n\n\nif __name__ == '__main__':\n\timport os\n\ttotal_position = {}\n\tfor i, file in enumerate(os.listdir(PATH)):\n\t # print(file)\n\t position = []\n\t if file.split('.')[1] == 'png':\n\t position = main(PATH+file)\n\t total_position[file] = position\n\t # if i > 25:\n\t # break\n\timport json\n\twith open('total_position.json', 'w') as f:\n\t json.dump(total_position, f, ensure_ascii=False, indent=2)\n\t# main(PATH+'20200308120114_1.jpg')\n","sub_path":"cropimage.py","file_name":"cropimage.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"544121678","text":"import argo.interaction\nfrom argo.interaction import HasProtocolState\n\nfrom typing import Any, List\n\nclass CryptolStartSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, name : str) -> None:\n super(CryptolStartSetup, self).__init__(\n 'SAW/Cryptol/start setup',\n {'name': name},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass CryptolLoadFile(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, filename : str) -> None:\n super(CryptolLoadFile, self).__init__(\n 'SAW/Cryptol/load file',\n {'file': filename},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass CryptolLoadModule(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, module_name : str) -> None:\n super(CryptolLoadModule, self).__init__(\n 'SAW/Cryptol/load module',\n {'module': module_name},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass CryptolFinishSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState) -> None:\n super(CryptolFinishSetup, self).__init__(\n 'SAW/Cryptol/finish setup',\n {},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMStartSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, name : str) -> None:\n super(LLVMStartSetup, self).__init__(\n 'SAW/LLVM/start setup',\n {'name': name},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMFinishSetup(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState) -> None:\n super(LLVMFinishSetup, self).__init__('SAW/LLVM/finish setup', {}, connection)\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMLoadModule(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState,\n name : str,\n bitcode_file : str) -> None:\n super(LLVMLoadModule, self).__init__(\n 'SAW/LLVM/load module',\n {'name': name, 'bitcode file': bitcode_file},\n connection\n )\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMReturn(argo.interaction.Command):\n def __init__(self, connection : HasProtocolState, return_value : Any) -> None:\n super(LLVMReturn, self).__init__('SAW/LLVM/return', {'value': return_value}, connection)\n\n def process_result(self, _res : Any) -> Any:\n return None\n\nclass LLVMVerify(argo.interaction.Command):\n def __init__(\n self,\n connection : HasProtocolState,\n module : str,\n function : str,\n lemmas : List[str],\n check_sat : bool,\n setup : str,\n tactic : str,\n lemma_name : str) -> None:\n params = {'module': module,\n 'function': function,\n 'lemmas': lemmas,\n 'check sat': check_sat,\n 'setup': setup,\n 'tactic': tactic,\n 'lemma name': lemma_name}\n super(LLVMVerify, self).__init__('SAW/LLVM/verify', params, connection)\n\n def process_result(self, _res : Any) -> Any:\n return None\n","sub_path":"python/saw/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"169526097","text":"phrase = input(\"Give me a phrase\\n\")\n\ndef create_thesaurus(filename):\n fread = open(filename, 'r')\n thesaurus = {}\n for line in fread:\n line = line.strip() #Gives back a new string without the \\n at the end\n line_parts = line.split(',')\n key = line_parts[0]\n value = line_parts[1:]\n thesaurus[key] = value\n return thesaurus\n\ndef removing_punctuation(phrase):\n new_string = \"\"\n for character in phrase:\n if character.isalpha() == False and character.isnumeric() == False and character.isspace() == False:\n continue\n else:\n new_string += character\n return new_string\n\ndef substituting_words(phrase, filename):\n import random\n thesaurus = create_thesaurus(filename)\n phrase_minus_punctuation = removing_punctuation(phrase)\n word_list = phrase_minus_punctuation.split(' ')\n new_phrase = []\n for word in word_list:\n key = word.lower()\n if key in thesaurus:\n list_of_synonyms = thesaurus[key]\n random_word = random.choice(list_of_synonyms)\n new_phrase.append(random_word.upper())\n else:\n new_phrase.append(word)\n new_string = ' '.join(new_phrase)\n return new_string\n \n \nprint(substituting_words(phrase, 'thesaurus.txt'))\n","sub_path":"Python/Class 10/lousy_plasma2.py","file_name":"lousy_plasma2.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"172645216","text":"import requests\nimport sqlite3\nimport datetime\nimport random\nimport json\ndb = '__HOME__/team29/commands.db'\nauthorized_users = ['ch3nj']\n\ncommands = {0: 'forward', 1: 'back', 2: 'left', 3: 'right'}\n\ndef request_handler(request):\n random.seed()\n if request['method'] == 'GET':\n values = request['values']\n if values['type'] == 'command':\n conn = sqlite3.connect(db)\n c = conn.cursor()\n out = None\n try:\n c.execute('''CREATE TABLE command_table (command int, timing timestamp);''')\n out = \"database constructed\"\n except:\n recent = datetime.datetime.now()- datetime.timedelta(seconds = 15)\n recent_commands = c.execute('''SELECT * FROM command_table WHERE timing > ? ORDER BY timing DESC''',(recent,)).fetchall()\n if len(recent_commands) == 0:\n out = 'stop'\n else:\n out = commands[recent_commands[random.randint(0, len(recent_commands)-1)][0]]\n conn.commit()\n conn.close()\n return out\n if values['type'] == 'graph':\n conn = sqlite3.connect(db)\n c = conn.cursor()\n out = []\n recent = datetime.datetime.now()- datetime.timedelta(seconds = 15)\n for num in commands:\n out.append({'command': commands[num], 'amount': len(c.execute('''SELECT * FROM command_table WHERE command = ? AND timing > ? ORDER BY timing DESC''',(num, recent)).fetchall())})\n conn.close()\n return json.dumps(out)\n\n elif request['method'] == 'POST':\n conn = sqlite3.connect(db)\n c = conn.cursor()\n command = request['form']['command']\n c.execute('''INSERT into command_table VALUES (?,?)''',(command, datetime.datetime.now())).fetchall()\n conn.commit()\n conn.close()\n return \"done\"\n","sub_path":"server/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"103958815","text":"# Copyright 2016 The Pixeldp Authors. All Rights Reserved.\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# Based on https://github.com/tensorflow/models/tree/master/research/resnet\n\n\"\"\"ResNet Train/Eval module.\n\"\"\"\nimport time\nimport six\nimport sys\nimport os\nimport json\n\nimport cifar_input\nimport numpy as np\nimport pixeldp_resnet_conv1\nimport pixeldp_resnet_img_noise\nimport pixeldp_cnn_conv1\n# import pixeldp_resnet_img_noise\nimport tensorflow as tf\n\nimport utils\n\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_string('dataset', 'cifar10', 'cifar10 or cifar100.')\ntf.app.flags.DEFINE_string('mode', 'train', 'train or eval.')\n# Download CIFAR10 or CIFAR100 from:\n# e.g. https://www.cs.toronto.edu/~kriz/cifar-100-binary.tar.gz\ntf.app.flags.DEFINE_string('train_data_path',\n '/home/mathias/data/cifar10_data/cifar-10-batches-bin/data_batch*',\n 'Filepattern for training data.')\ntf.app.flags.DEFINE_string('eval_data_path',\n '/home/mathias/data/cifar10_data/cifar-10-batches-bin/test_batch*',\n 'Filepattern for eval data')\ntf.app.flags.DEFINE_string('model_dir', 'model',\n 'Directory to keep training outputs.')\ntf.app.flags.DEFINE_integer('eval_data_size', 5000,\n 'Size of test set to eval on.')\ntf.app.flags.DEFINE_integer('max_steps', 60000,\n 'Max number of steps for training a model.')\ntf.app.flags.DEFINE_string('data_dir', 'data',\n 'Directory to keep the checkpoints. Should be a '\n 'parent directory of FLAGS.model_dir.')\ntf.app.flags.DEFINE_integer('num_gpus', 1,\n 'Number of gpus used for training. (0 or 1)')\n\ndef evaluate(hps, model, dir_name=None, rerun=False):\n \"\"\"Evaluate the ResNet and log prediction counters to compute\n sensitivity.\"\"\"\n if dir_name == None:\n dir_name = FLAGS.data_dir + \"/\" + FLAGS.model_dir\n\n if os.path.isfile(dir_name + \"/eval_data.json\") and not rerun:\n # run only new models\n return\n\n if FLAGS.dataset == 'mnist':\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n dataset = mnist.test\n images = tf.placeholder(tf.float32,\n [hps.batch_size, 784],\n name='x-input')\n labels = tf.placeholder(tf.int64,\n [hps.batch_size],\n name='y-input')\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n images, labels = cifar_input.build_input(\n FLAGS.dataset,\n FLAGS.eval_data_path,\n hps.batch_size,\n hps.image_standardization,\n FLAGS.mode\n )\n model = model.Model(hps, images, labels, FLAGS.mode)\n model.build_graph()\n saver = tf.train.Saver()\n summary_writer = tf.summary.FileWriter(dir_name)\n\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\n tf.train.start_queue_runners(sess)\n\n best_precision = 0.0\n try:\n ckpt_state = tf.train.get_checkpoint_state(dir_name)\n except tf.errors.OutOfRangeError as e:\n tf.logging.error('Cannot restore checkpoint: %s', e)\n\n tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)\n saver.restore(sess, ckpt_state.model_checkpoint_path)\n\n # Make predictions on the dataset, keep the label distribution\n data = {\n 'predictions': [],\n 'pred_truth': [],\n }\n total_prediction, correct_prediction = 0, 0\n eval_data_size = FLAGS.eval_data_size\n eval_batch_size = hps.batch_size\n eval_batch_count = int(eval_data_size / eval_batch_size)\n for i in six.moves.range(eval_batch_count):\n if FLAGS.dataset == 'mnist':\n xs, ys = dataset.next_batch(hps.batch_size, fake_data=False)\n args = {model.noise_scale: 1.0,\n model._images: xs,\n model._labels: ys}\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n args = {model.noise_scale: 1.0}\n\n (\n summaries,\n loss,\n predictions,\n truth,\n train_step,\n ) = sess.run(\n [\n model.summaries,\n model.cost,\n model.predictions,\n model.labels,\n model.global_step,\n ],\n args)\n\n print(\"Done: {}/{}\".format(eval_batch_size*i, eval_data_size))\n truth = np.argmax(truth, axis=1)[:hps.batch_size]\n prediction_votes = np.zeros([hps.batch_size, hps.num_classes])\n predictions = np.argmax(predictions, axis=1)\n for i in range(hps.n_draws):\n for j in range(hps.batch_size):\n prediction_votes[j, predictions[i*hps.batch_size + j]] += 1\n predictions = np.argmax(prediction_votes, axis=1)\n\n data['predictions'] += prediction_votes.tolist()\n data['pred_truth'] += (truth == predictions).tolist()\n\n print(\"{} / {}\".format(np.sum(truth == predictions), len(predictions)))\n\n correct_prediction += np.sum(truth == predictions)\n total_prediction += predictions.shape[0]\n\n current_precision = 1.0 * correct_prediction / total_prediction\n print(current_precision)\n print()\n\n # For Parseval, get true sensitivity, use to rescale the actual attack\n # bound as the nosie assumes this to be 1 but often it is not.\n if hps.noise_scheme == 'l2_l2_s1':\n # Parseval updates usually have a sensitivity higher than 1\n # despite the projection: we need to rescale when computing\n # sensitivity.\n sensitivity_multiplier = float(sess.run(\n model.sensitivity_multiplier,\n {model.noise_scale: 1.0}\n ))\n else:\n sensitivity_multiplier = 1.0\n with open(dir_name + \"/sensitivity_multiplier.json\", 'w') as f:\n d = [sensitivity_multiplier]\n f.write(json.dumps(d))\n\n # Compute robustness and add it to the eval data.\n dp_mechs = {\n 'l2_l2_s1': 'gaussian',\n 'l1_l2_s1': 'gaussian',\n 'l1_l1_s1': 'laplace',\n 'l1_l1': 'laplace',\n 'l1_l2': 'gaussian',\n 'l2': 'gaussian',\n 'l1': 'laplace',\n }\n robustness = [utils.robustness_size(\n counts=x,\n dp_attack_size=hps.attack_norm_bound,\n dp_epsilon=1.0,\n dp_delta=0.05,\n dp_mechanism=dp_mechs[hps.noise_scheme]\n ) / sensitivity_multiplier for x in data['predictions']]\n data['robustness'] = robustness\n data['sensitivity_mult_used'] = sensitivity_multiplier\n\n # Log eval data\n with open(dir_name + \"/eval_data.json\", 'w') as f:\n f.write(json.dumps(data))\n\n # Print stuff\n precision = 1.0 * correct_prediction / total_prediction\n best_precision = max(precision, best_precision)\n\n precision_summ = tf.Summary()\n precision_summ.value.add(\n tag='Precision', simple_value=precision)\n summary_writer.add_summary(precision_summ, train_step)\n best_precision_summ = tf.Summary()\n best_precision_summ.value.add(\n tag='Best Precision', simple_value=best_precision)\n summary_writer.add_summary(best_precision_summ, train_step)\n summary_writer.add_summary(summaries, train_step)\n tf.logging.info('loss: %.3f, precision: %.3f, best precision: %.3f' %\n (loss, precision, best_precision))\n summary_writer.flush()\n\ndef train(hps, model, dir_name=None):\n \"\"\"Training loop.\"\"\"\n if dir_name == None:\n dir_name = FLAGS.data_dir + \"/\" + FLAGS.model_dir\n\n if FLAGS.dataset == 'mnist':\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n dataset = mnist.train\n images = tf.placeholder(tf.float32,\n [hps.batch_size, 784],\n name='x-input')\n labels = tf.placeholder(tf.int64,\n [hps.batch_size],\n name='y-input')\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n images, labels = cifar_input.build_input(\n FLAGS.dataset,\n FLAGS.eval_data_path,\n hps.batch_size,\n hps.image_standardization,\n FLAGS.mode\n )\n model = model.Model(hps, images, labels, FLAGS.mode)\n model.build_graph()\n\n param_stats = tf.contrib.tfprof.model_analyzer.print_model_analysis(\n tf.get_default_graph(),\n tfprof_options=tf.contrib.tfprof.model_analyzer.\n TRAINABLE_VARS_PARAMS_STAT_OPTIONS)\n sys.stdout.write('total_params: %d\\n' % param_stats.total_parameters)\n\n tf.contrib.tfprof.model_analyzer.print_model_analysis(\n tf.get_default_graph(),\n tfprof_options=tf.contrib.tfprof.model_analyzer.FLOAT_OPS_OPTIONS)\n\n truth = tf.argmax(model.labels, axis=1)\n predictions = tf.argmax(model.predictions, axis=1)\n one_hot_preds = tf.one_hot(predictions, depth=hps.num_classes, dtype=tf.float32)\n votes = tf.reshape(one_hot_preds, [hps.n_draws, hps.batch_size, hps.num_classes])\n predictions = tf.argmax(tf.reduce_sum(votes, axis=0), axis=1)\n precision = tf.reduce_mean(tf.to_float(tf.equal(predictions, truth)))\n\n summary_hook = tf.train.SummarySaverHook(\n save_steps=100,\n output_dir=dir_name,\n summary_op=tf.summary.merge([model.summaries,\n tf.summary.scalar('Precision', precision)]))\n\n logging_hook = tf.train.LoggingTensorHook(\n tensors={'step': model.global_step,\n 'loss': model.cost,\n 'precision': precision},\n every_n_iter=100)\n\n class _LearningRateSetterHook(tf.train.SessionRunHook):\n \"\"\"Sets learning_rate based on global step.\"\"\"\n\n def begin(self):\n self._lrn_rate = 0.1\n self._schedule = list(zip(hps.lrn_rte_changes, hps.lrn_rte_vals))\n\n def before_run(self, run_context):\n return tf.train.SessionRunArgs(\n model.global_step, # Asks for global step value.\n feed_dict={model.lrn_rate: self._lrn_rate}) # Sets learning rate\n\n def after_run(self, run_context, run_values):\n train_step = run_values.results\n if len(self._schedule) > 0 and train_step >= self._schedule[0][0]:\n # Update learning rate according to the schedule.\n self._lrn_rate = self._schedule[0][1]\n self._schedule = self._schedule[1:]\n\n print(\"START TRAINING\")\n steps = 0\n with tf.train.MonitoredTrainingSession(\n checkpoint_dir=dir_name,\n hooks=[logging_hook,\n _LearningRateSetterHook(),\n tf.train.StopAtStepHook(last_step=FLAGS.max_steps),],\n chief_only_hooks=[summary_hook],\n # Since we provide a SummarySaverHook, we need to disable default\n # SummarySaverHook. To do that we set save_summaries_steps to 0.\n save_summaries_steps=0,\n config=tf.ConfigProto(allow_soft_placement=True)) as mon_sess:\n while not mon_sess.should_stop():\n s = 1.0 - min(0.99975**steps, 0.9)\n if s > 0.9: s = 1.0 # this triggers around 10k steps\n\n if FLAGS.dataset == 'mnist':\n xs, ys = dataset.next_batch(hps.batch_size, fake_data=False)\n args = {model.noise_scale: s,\n model._images: xs,\n model._labels: ys}\n elif FLAGS.dataset == 'cifar10' or FLAGS.dataset == 'cifar100':\n args = {model.noise_scale: s}\n\n mon_sess.run(model.train_op, args)\n steps += 1\n\ndef run_one():\n if FLAGS.num_gpus == 0:\n dev = '/cpu:0'\n elif FLAGS.num_gpus == 1:\n dev = '/gpu:0'\n else:\n raise ValueError('Only support 0 or 1 gpu.')\n\n if FLAGS.dataset == 'mnist':\n image_size = 28\n num_classes = 10\n relu_leakiness = 0.0\n lrn_rate = 0.01\n lrn_rte_changes = []\n lrn_rte_vals = []\n if FLAGS.mode == 'train':\n batch_size = 128\n n_draws = 1\n elif FLAGS.mode == 'eval':\n batch_size = 100\n n_draws = 500\n else:\n lrn_rate = 0.1\n lrn_rte_changes = [40000, 60000, 80000]\n lrn_rte_vals = [0.01, 0.001, 0.0001]\n if FLAGS.mode == 'train':\n batch_size = 128\n n_draws = 1\n elif FLAGS.mode == 'eval':\n batch_size = 4\n n_draws = 500\n\n if FLAGS.dataset == 'cifar10':\n image_size = 32\n num_classes = 10\n relu_leakiness = 0.1\n elif FLAGS.dataset == 'cifar100':\n image_size = 32\n num_classes = 100\n relu_leakiness = 0.1\n\n # noise_schemes for pixeldp_img_noise:\n # - l1: L1 attack bound, L1 sensitivity (Laplace mech.).\n # - l2: L2 attack bound, L2 sensitivity (Gaussian mech.).\n # noise_schemes for pixeldp_conv1:\n # - l1_l1: L1 attack bound with L1 sensitivity, reparametrization\n # trick (Laplace).\n # - l1_l1_s1: L1 attack bound with L1 sensitivity, sensitivity=1\n # (Laplace).\n # - l1_l2: L1 attack bound with L2 sensitivity, reparametrization\n # (Gaussian).\n # - l1_l2_s1: L1 attack bound with L2 sensitivity, sensitivity=1\n # (Gaussian).\n # - l2_l2_s1: L2 attack bound with L2 sensitivity, sensitivity<=1\n # (Gaussian).\n hps = utils.HParams(batch_size=batch_size,\n num_classes=num_classes,\n image_size=image_size,\n lrn_rate=lrn_rate,\n lrn_rte_changes=lrn_rte_changes,\n lrn_rte_vals=lrn_rte_vals,\n num_residual_units=4,\n use_bottleneck=False,\n weight_decay_rate=0.0002,\n relu_leakiness=relu_leakiness,\n optimizer='mom',\n image_standardization=False,\n dropout=False,\n n_draws=n_draws,\n noise_scheme='l2_l2_s1',\n attack_norm_bound=0.3)\n\n # _model can be:\n # pixeldp_resnet_conv1 pixeldp_resnet_img_noise\n # pixeldp_cnn_conv1 pixeldp_cnn_img_noise\n _model = pixeldp_cnn_conv1\n with tf.device(dev):\n if FLAGS.mode == 'train':\n train(hps, _model)\n elif FLAGS.mode == 'eval':\n evaluate(hps, _model)\n\ndef main(_):\n run_one()\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"125165767","text":"# ex:ts=4:sw=4:sts=4:et\n# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-\nfrom __future__ import absolute_import\nimport re\nimport json\nimport copy\nimport os\n\nfrom svtplay_dl.service import Service\nfrom svtplay_dl.utils import filenamify\nfrom svtplay_dl.log import log\nfrom svtplay_dl.fetcher.rtmp import RTMP\nfrom svtplay_dl.fetcher.hls import hlsparse\nfrom svtplay_dl.subtitle import subtitle\nfrom svtplay_dl.error import ServiceError\n\n\nclass Kanal5(Service):\n supported_domains = ['kanal5play.se', 'kanal9play.se', 'kanal11play.se']\n\n def __init__(self, url):\n Service.__init__(self, url)\n self.cookies = {}\n self.subtitle = None\n\n def get(self, options):\n match = re.search(r\".*video/([0-9]+)\", self.url)\n if not match:\n yield ServiceError(\"Can't find video file\")\n return\n\n video_id = match.group(1)\n if options.username and options.password:\n # get session cookie\n data = self.http.request(\"get\", \"http://www.kanal5play.se/\", cookies=self.cookies)\n authurl = \"https://kanal5swe.appspot.com/api/user/login?callback=jQuery171029989&email=%s&password=%s&_=136250\" % \\\n (options.username, options.password)\n data = self.http.request(\"get\", authurl, cookies=data.cookies).text\n match = re.search(r\"({.*})\\);\", data)\n jsondata = json.loads(match.group(1))\n if jsondata[\"success\"] is False:\n yield ServiceError(jsondata[\"message\"])\n return\n authToken = jsondata[\"userData\"][\"auth\"]\n self.cookies = {\"authToken\": authToken}\n options.cookies = self.cookies\n\n url = \"http://www.kanal5play.se/api/getVideo?format=FLASH&videoId=%s\" % video_id\n data = self.http.request(\"get\", url, cookies=self.cookies).text\n data = json.loads(data)\n options.cookies = self.cookies\n if not options.live:\n options.live = data[\"isLive\"]\n\n if options.output_auto:\n directory = os.path.dirname(options.output)\n options.service = \"kanal5\"\n\n title = \"%s-s%s-%s-%s-%s\" % (data[\"program\"][\"name\"], data[\"seasonNumber\"], data[\"episodeText\"], data[\"id\"], options.service)\n title = filenamify(title)\n if len(directory):\n options.output = os.path.join(directory, title)\n else:\n options.output = title\n\n if self.exclude(options):\n yield ServiceError(\"Excluding video\")\n return\n\n if data[\"hasSubtitle\"]:\n yield subtitle(copy.copy(options), \"json\", \"http://www.kanal5play.se/api/subtitles/%s\" % video_id)\n\n if options.force_subtitle:\n return\n\n show = True\n if \"streams\" in data.keys():\n for i in data[\"streams\"]:\n if i[\"drmProtected\"]:\n yield ServiceError(\"We cant download drm files for this site.\")\n return\n steambaseurl = data[\"streamBaseUrl\"]\n bitrate = i[\"bitrate\"]\n if bitrate > 1000:\n bitrate = bitrate / 1000\n options2 = copy.copy(options)\n options2.other = \"-W %s -y %s \" % (\"http://www.kanal5play.se/flash/K5StandardPlayer.swf\", i[\"source\"])\n options2.live = True\n yield RTMP(options2, steambaseurl, bitrate)\n\n url = \"http://www.kanal5play.se/api/getVideo?format=IPAD&videoId=%s\" % video_id\n data = self.http.request(\"get\", url, cookies=self.cookies)\n data = json.loads(data.text)\n if \"reasonsForNoStreams\" in data:\n show = False\n if \"streams\" in data.keys():\n for i in data[\"streams\"]:\n streams = hlsparse(options, self.http.request(\"get\", i[\"source\"]), i[\"source\"])\n for n in list(streams.keys()):\n yield streams[n]\n if \"reasonsForNoStreams\" in data and show:\n yield ServiceError(data[\"reasonsForNoStreams\"][0])\n\n def find_all_episodes(self, options):\n program = re.search(\".*/program/(\\d+)\", self.url)\n if not program:\n log.error(\"Can't find program id in url\")\n return None\n baseurl = \"http://www.kanal5play.se/content/program/%s\" % program.group(1)\n data = self.http.request(\"get\", baseurl).text\n sasong = re.search(\"/program/\\d+/sasong/(\\d+)\", data)\n if not sasong:\n log.error(\"Can't find seasong id\")\n return None\n seasong = int(sasong.group(1))\n episodes = []\n n = 0\n more = True\n while more:\n url = \"%s/sasong/%s\" % (baseurl, seasong)\n data = self.http.request(\"get\", url)\n if data.status_code == 404:\n more = False\n else:\n regex = re.compile(r'href=\"(/play/program/\\d+/video/\\d+)\"')\n for match in regex.finditer(data.text):\n if n == options.all_last:\n break\n url2 = \"http://www.kanal5play.se%s\" % match.group(1)\n if url2 not in episodes:\n episodes.append(url2)\n n += 1\n seasong -= 1\n\n return episodes\n","sub_path":"lib/svtplay_dl/service/kanal5.py","file_name":"kanal5.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"371093344","text":"from django.urls import path\nfrom .views import (index, MailHtml, Staff, Logout, Login, login_html, StaffDailyList, DailyCreate, news , SecurityNews,\n SecurityNewsDetail, AllStaffDetail, RssNews, SelfNews, ApiAllStaffDetail, ApiStaffDetail,\n DeleteDaily)\n\nurlpatterns = [\n # path('/', admin.site.urls),\n path('', SelfNews.as_view()),\n path('safe', SecurityNews.as_view()),\n path('feed', RssNews.as_view()),\n path('sendmail', MailHtml.as_view()),\n path('staffinfo', Staff.as_view()),\n path('logout/', Logout.as_view(), name=\"logout\"),\n path('accounts/login/', login_html, name=\"login\"),\n # path('auth/login/', Login.as_view()),\n path('daily//', StaffDailyList.as_view(), name='StaffDailyList'),\n path('create/daily/', DailyCreate.as_view()),\n path('news/', SecurityNews.as_view()),\n path('news//', SecurityNewsDetail.as_view(), name=\"news-detail\"),\n path('index/', index),\n path('alldaily', AllStaffDetail.as_view()),\n path('api/all_detail', ApiAllStaffDetail.as_view()),\n path('api/staff_detail//', ApiStaffDetail.as_view()),\n path('delete/', DeleteDaily.as_view()),\n]\n","sub_path":"scheduled/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"237052495","text":"from django.shortcuts import render\nfrom facebook_business.adobjects.adsinsights import AdsInsights\nfrom facebook_business.adobjects.campaign import Campaign as RemoteCampaign\n\nfrom app.service.adaccount_service import AdAccountService\nfrom app.views.constants import DATE_PRESET_CHOICES\nfrom copy import deepcopy\n\nADACCOUNT_CHOICES = [\n ('this_adaccount', 'Tài khoản hiện tại'),\n ('all_adaccounts', 'Tất cả tài khoản')\n]\n\nOBJECTIVE_CHOICES = {\n (RemoteCampaign.Objective.post_engagement, \"Tương tác\"),\n (RemoteCampaign.Objective.conversions, \"Chuyển đổi\"),\n (RemoteCampaign.Objective.messages, \"Tin nhắn\"),\n (RemoteCampaign.Objective.video_views, 'Xem video')\n}\n\nBREAKDOWNS_CHOICES = [\n (AdsInsights.Breakdowns.impression_device, 'Thiết bị hiển thị'),\n (AdsInsights.Breakdowns.age, 'Độ tuổi'),\n (AdsInsights.Breakdowns.gender, 'Giới tính'),\n (AdsInsights.Breakdowns.region, 'Tỉnh thành'),\n (AdsInsights.Breakdowns.publisher_platform, 'Nền tảng'),\n (AdsInsights.Breakdowns.device_platform, 'Thiết bị'),\n (AdsInsights.Breakdowns.hourly_stats_aggregated_by_advertiser_time_zone, 'Giờ trong ngày'),\n ('publisher_platform_platform_position', 'Vị trí hiển thị'),\n ('age_gender', 'Độ tuổi + giới tính'),\n ('publisher_platform_platform_position_impression_device', 'Vị trí + thiết bị hiển thị'),\n]\n\n\ndef analysis(request):\n params = {\n 'objective' : request.GET.get('objective', RemoteCampaign.Objective.post_engagement),\n 'date_preset': request.GET.get('date_preset', AdsInsights.DatePreset.last_30d),\n 'breakdowns' : request.GET.get('breakdowns', AdsInsights.Breakdowns.impression_device),\n 'adaccount' : request.GET.get('adaccount', ADACCOUNT_CHOICES[0][0])\n }\n if params['breakdowns'] == 'publisher_platform_platform_position_impression_device':\n params['breakdowns'] = ['publisher_platform', 'platform_position', 'impression_device']\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n params['breakdowns'] = 'publisher_platform_platform_position_impression_device'\n elif params['breakdowns'] == 'publisher_platform_platform_position':\n params['breakdowns'] = ['publisher_platform', 'platform_position']\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n params['breakdowns'] = 'publisher_platform_platform_position'\n elif params['breakdowns'] == 'age_gender':\n params['breakdowns'] = ['age', 'gender']\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n params['breakdowns'] = 'age_gender'\n else:\n adsinsights_dlist = AdAccountService.get_adsinsight_by_breakdowns(**params)\n\n summary = AdAccountService.get_adsinsight_by_breakdowns_summary(adsinsights_dlist)\n\n context = {\n \"OBJECTIVE_CHOICES\" : OBJECTIVE_CHOICES,\n \"BREAKDOWNS_CHOICES\" : BREAKDOWNS_CHOICES,\n \"DATE_PRESET_CHOICES\": DATE_PRESET_CHOICES,\n \"ADACCOUNT_CHOICES\" : ADACCOUNT_CHOICES,\n \"adsinsights_dlist\" : adsinsights_dlist,\n \"params\" : params,\n \"summary\" : summary\n }\n\n return render(request, \"app/analysis/analysis.html\", context)\n","sub_path":"app/views/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"158247672","text":"from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.shortcuts import get_object_or_404, render\n\nfrom .models import Category, Product, ProductImage\n\n\ndef product_all(request):\n products = Product.objects.prefetch_related('product_image').filter(is_active=True)\n return render(request, 'catalogue/index.html', {'products': products})\n\n\ndef category_list(request, category_slug=None):\n category = get_object_or_404(Category, slug=category_slug)\n products = Product.objects.filter(\n category__in=Category.objects.get(slug=category_slug).get_descendants(include_self=True)\n )\n paginator = Paginator(products, 10)\n page = request.GET.get('page')\n try:\n product = paginator.page(page)\n except PageNotAnInteger:\n product = paginator.page(1)\n except EmptyPage:\n product = paginator.page(paginator.num_pages)\n return render(request, 'catalogue/category.html', {\n 'category': category,\n 'products': products,\n 'page': page,\n 'product': product,\n })\n\n\ndef product_detail(request, slug):\n product = get_object_or_404(Product, slug=slug, is_active=True)\n\n return render(request, 'catalogue/single.html', {'product': product})\n\n\n\n\n\n\n","sub_path":"ecommerce/ecommerce/apps/catalogue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"83599177","text":"from numpy import sin, cos, cumsum, dot, zeros\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom sympy.physics.mechanics import kinetic_energy\nfrom numpy import array, linspace, deg2rad, ones, concatenate\nfrom sympy import lambdify, atan, atan2, Matrix, simplify\nfrom sympy.mpmath import norm\nfrom pydy.codegen.code import generate_ode_function\nfrom scipy.integrate import odeint\nimport math\nimport numpy as np\nimport single_pendulum_setup as sp\nimport double_pendulum_particle_setup as pp\nimport double_pendulum_rb_setup as rb\nimport triple_pendulum_setup as tp\nimport pickle\n\n\n\nnumerical_constants = array([0.5,\n 0.5,\n 0.75,\n 0.75,\n 1.0,\n 1.0,\n 9.81])\n\nparameter_dict = dict(zip(tp.constants, numerical_constants))\n\n\ngravity_dict = dict(zip([sp.g, pp.g, rb.g, tp.g], [9.81,9.81, 9.81, 9.81]))\nglobal_mass_dict = dict(zip([sp.s_mass], [tp.a_mass+tp.b_mass+tp.c_mass]))\nsp_forcing = -1*simplify(sp.forcing - sp.s_torque) + sp.s_torque\nsp_eq = (sp.mass_matrix.inv()*sp_forcing)[0].subs(gravity_dict)\nsp_eq_torque_only = sp.s_torque*(sp.mass_matrix.inv())[0].subs(global_mass_dict).subs(parameter_dict)\nsp_eq = sp_eq.subs(global_mass_dict).subs(parameter_dict)\n\nsp_eq_string = str(sp_eq)\nsp_eq_vars = str([sp.s_length, sp.theta_s, sp.s_torque])\nfile = open('sp_eq.pkl', 'wb')\npickle.dump([sp_eq_string, sp_eq_vars], file)\nfile.close()\n\nsp_eq_torque_only_string = str(sp_eq)\nsp_eq_torque_only_vars = str([sp.s_length, sp.s_torque])\nfile = open('sp_eq_torque_only.pkl', 'wb')\npickle.dump([sp_eq_torque_only_string, sp_eq_torque_only_vars], file)\nfile.close()\n\n\ncom_eq_string = str(tp.com.subs(parameter_dict))\ncom_eq_vars = str((tp.theta_a, tp.theta_b, tp.theta_c))\nfile = open('com_eq.pkl', 'wb')\npickle.dump([com_eq_string, com_eq_vars], file)\nfile.close()\n\n\n\ncom_dot_eq_string = str(tp.com_dot.subs(parameter_dict))\ncom_dot_eq_vars = str([tp.theta_a, tp.theta_b, tp.theta_c, \n tp.omega_a, tp.omega_b, tp.omega_c])\nfile = open('com_dot_eq.pkl', 'wb')\npickle.dump([com_dot_eq_string, com_dot_eq_vars], file)\nfile.close()\n\n\nsolved_pp_com_ddot_t1_string = str(pp.des_t1_acc)\nsolved_pp_com_ddot_t1_vars = str([pp.one_length, pp.two_length, pp.one_mass, pp.two_mass, pp.theta1, pp.theta2, pp.omega1, pp.omega2, pp.des_com_ang_acc_x, pp.des_com_ang_acc_y])\nfile = open('solved_pp_com_ddot_t1.pkl', 'wb')\npickle.dump([solved_pp_com_ddot_t1_string, solved_pp_com_ddot_t1_vars], file)\nfile.close()\n\n\nsolved_pp_com_ddot_t2_string = str(pp.des_t2_acc)\nsolved_pp_com_ddot_t2_vars = str([pp.one_length, pp.two_length, pp.one_mass, pp.two_mass, pp.theta1, pp.theta2, pp.omega1, pp.omega2, pp.des_com_ang_acc_x, pp.des_com_ang_acc_y])\nfile = open('solved_pp_com_ddot_t2.pkl', 'wb')\npickle.dump([solved_pp_com_ddot_t2_string, solved_pp_com_ddot_t2_vars], file)\nfile.close()\n\n\nsolved_rb_com_ddot_t1_string = str(rb.des_t1_acc)\nsolved_rb_com_ddot_t1_vars = str([rb.one_length, rb.one_com_x, rb.one_com_y, rb.two_com_x, rb.two_com_y, rb.one_mass, rb.two_mass, rb.theta1, rb.theta2, rb.omega1, rb.omega2, rb.des_com_ang_acc_x, rb.des_com_ang_acc_y])\nfile = open('solved_rb_com_ddot_t1.pkl', 'wb')\npickle.dump([solved_rb_com_ddot_t1_string, solved_rb_com_ddot_t1_vars], file)\nfile.close()\n\n\nsolved_rb_com_ddot_t2_string = str(rb.des_t2_acc)\nsolved_rb_com_ddot_t2_vars = str([rb.one_length, rb.one_com_x, rb.one_com_y, rb.two_com_x, rb.two_com_y, rb.one_mass, rb.two_mass, rb.theta1, rb.theta2, rb.omega1, rb.omega2, rb.des_com_ang_acc_x, rb.des_com_ang_acc_y])\nfile = open('solved_rb_com_ddot_t2.pkl', 'wb')\npickle.dump([solved_rb_com_ddot_t2_string, solved_rb_com_ddot_t2_vars], file)\nfile.close()\n\nbc_com_string = str(tp.com_bc_in_a.subs(parameter_dict))\nbc_com_vars = str([tp.theta_b, tp.theta_c])\nfile = open('bc_com.pkl', 'wb')\npickle.dump([bc_com_string, bc_com_vars], file)\nfile.close()\n\n\nbc_com_inertial_string = str(tp.com_bc.subs(parameter_dict))\nbc_com_inertial_vars = str([tp.theta_a, tp.theta_b, tp.theta_c])\nfile = open('bc_com_inertial.pkl', 'wb')\npickle.dump([bc_com_inertial_string, bc_com_inertial_vars], file)\nfile.close()\n\n\nbc_com_dot_string = str(tp.com_bc_dot_in_a.subs(parameter_dict))\nbc_com_dot_vars = str([tp.theta_b, tp.theta_c, tp.omega_b, tp.omega_c])\nfile = open('bc_com_dot.pkl', 'wb')\npickle.dump([bc_com_dot_string, bc_com_dot_vars], file)\nfile.close()\n\na_com_string = str(tp.com_a.subs(parameter_dict))\na_com_vars = str([tp.theta_a])\nfile = open('a_com.pkl', 'wb')\npickle.dump([a_com_string, a_com_vars], file)\nfile.close()\n\na_com_dot_string = str(tp.com_a_dot.subs(parameter_dict))\na_com_dot_vars = str([tp.theta_a, tp.omega_a])\nfile = open('a_com_dot.pkl', 'wb')\npickle.dump([a_com_dot_string, a_com_dot_vars], file)\nfile.close()\n\npp_inverse_dynamics_string = str( pp.inverse_dynamics.subs(gravity_dict))\npp_inverse_dynamics_vars = str([pp.one_length, pp.two_length, pp.one_mass, pp.two_mass, pp.theta1, pp.theta2, pp.omega1, pp.omega2, pp.alpha1, pp.alpha2])\nfile = open('pp_inverse_dynamics.pkl', 'wb')\npickle.dump([pp_inverse_dynamics_string, pp_inverse_dynamics_vars], file)\nfile.close()\n\n\nrb_inverse_dynamics_string = str(rb.inverse_dynamics.subs(gravity_dict))\nrb_inverse_dynamics_vars = str([rb.one_length, rb.one_com_x, rb.one_com_y, rb.two_com_x, rb.two_com_y, rb.one_com_x_dot, rb.one_com_y_dot, rb.two_com_x_dot, rb.two_com_y_dot, rb.one_mass, rb.two_mass, rb.theta1, rb.theta2, rb.omega1, rb.omega2, rb.alpha1, rb.alpha2])\nfile = open('rb_inverse_dynamics.pkl', 'wb')\npickle.dump([rb_inverse_dynamics_string, rb_inverse_dynamics_vars], file)\nfile.close()\n\nargs_ode_funcs = str([tp.mass_matrix_full, tp.forcing_vector_full, \n tp.constants, tp.coordinates,\n tp.speeds, tp.specified])\nfile = open('args_ode_funcs.pkl', 'wb')\npickle.dump(args_ode_funcs, file)\nfile.close()\n\n\n","sub_path":"equivalent_acrobot/pickle_funcs.py","file_name":"pickle_funcs.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"309475948","text":"from ..models.users import User\nimport time\nfrom vk.exceptions import VkAPIError\n\n\nclass Manager(object):\n def __init__(self, db_sessuib_class, bots, group_id):\n self.session = db_sessuib_class()\n self.bots = bots\n self.group_id = group_id\n\n def process(self):\n for bot in [b for b in self.bots if b.ready()]: # only ready bots\n try:\n self._invite_users(bot)\n except VkAPIError as e:\n if e.is_captcha_needed():\n print(e.message)\n bot.sleep(3)\n continue\n\n def _invite_users(self, bot):\n users = self.session.query(User).filter_by(bot_id=bot.uid) \\\n .filter_by(is_in_friend_list=True) \\\n .filter_by(is_group_invite_sent=False)\n\n for user in users:\n time.sleep(5)\n self._invite_specific_user(user, bot)\n\n self.session.commit()\n\n def _invite_specific_user(self, u, bot):\n is_member = bot.api.groups.isMember(\n group_id=self.group_id, user_id=u.uid)\n\n if not is_member:\n # if user not a member then (re)send group invite\n print('inviting user %s to group' % u.uid)\n bot.api.groups.invite(group_id=self.group_id, user_id=u.uid)\n\n # even if already in group set property to True\n # to prevent further invites\n u.is_group_invite_sent = True\n","sub_path":"inviter/modules/invite_manager.py","file_name":"invite_manager.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"49295419","text":"\"\"\"\n Capstone Project. Code written by PUT_YOUR_NAME_HERE.\n Fall term, 2018-2019.\n\"\"\"\n\nimport rosebotics_new as rb\nimport ev3dev.ev3 as ev3\nimport time\n\n\ndef main():\n \"\"\" Runs YOUR specific part of the project \"\"\"\n red = rb.Color.RED.value\n blue = rb.Color.BLUE.value\n green = rb.Color.GREEN.value\n nocolor = rb.Color.NO_COLOR.value\n brown = rb.Color.BROWN.value\n white = rb.Color.WHITE.value\n yellow = rb.Color.YELLOW.value\n black = rb.Color.BLACK.value\n\n # robot = rb.Snatch3rRobot()\n # robot.drive_system.go_straight_inches(20)\n drive_polygon(5, 10)\n # line_follow()\n # drive_until_color(red)\n # robot.drive_system.turn_degrees\n #detectItem()\n # ColorSorting(red, blue, green, yellow, green)\n\ndef detectItem():\n robot = rb.Snatch3rRobot()\n sensor = robot.proximity_sensor\n\n while True:\n if ((70 * ((sensor.get_distance_to_nearest_object())/100)) < 15) and ((70 * ((sensor.get_distance_to_nearest_object())/100)) > 9):\n ev3.Sound.beep()\n\n\n\ndef drive_polygon(n, inches):\n x = rb.Snatch3rRobot()\n drivesystem = x.drive_system\n # degrees = ((n - 2) * 180) / n\n # degrees = 180 - degrees\n degrees = (360/n)\n\n for k in range(n):\n drivesystem.go_straight_inches(inches)\n drivesystem.spin_in_place_degrees(-degrees)\n\n\ndef line_follow():\n robot = rb.Snatch3rRobot()\n drivesystem = robot.drive_system\n colorsensor = robot.color_sensor\n drivesystem.start_moving()\n while True:\n if colorsensor.get_reflected_intensity() > 10:\n drivesystem.spin_in_place_degrees(10)\n drivesystem.start_moving(50,50)\n\n\ndef drive_until_color(color):\n robot = rb.Snatch3rRobot()\n drivesystem = robot.drive_system\n colorsensor = robot.color_sensor\n drivesystem.start_moving(50,50)\n\n while True:\n colorsensor.wait_until_color_is(color)\n drivesystem.stop_moving()\n break\n\n\n\n\n# Capstone Project\n\ndef ColorSorting(red, white, yellow, black, green):\n robot = rb.Snatch3rRobot()\n colorsensor = robot.color_sensor\n drivesystem = robot.drive_system\n ev3.Sound.set_volume(100)\n drivesystem.start_moving(20,20)\n\n while True:\n if colorsensor.get_color() == red:\n ev3.Sound.speak(\"Hello\")\n if colorsensor.get_color() == white:\n ev3.Sound.speak(\"to\")\n if colorsensor.get_color() == yellow:\n ev3.Sound.speak(\"the\")\n if colorsensor.get_color() == black:\n ev3.Sound.speak(\"world\")\n if colorsensor.get_color() == green:\n ev3.Sound.speak(\"Greetings humans\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nmain()\n","sub_path":"src/harrisap.py","file_name":"harrisap.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"580308518","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport re\nimport sys\nfrom pyspark import SparkConf, SparkContext\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\n\n\n# In[ ]:\n\n\n#set context\nconf = SparkConf()\nsc = SparkContext(conf=conf)\n\n\n# In[ ]:\n\n\nmax_iter = 20\nclusters = 10\n\n\n# In[ ]:\n\n\ndef split(l):\n line=l.split(' ')\n val = [float(s) for s in line if s is not ''] \n return tuple(val)\n\ndef combine_with_cluster(l,clu):\n return [(l,c) for c in clu]\n\ndef calc_dist(l, norm=2):\n dist = np.linalg.norm(np.array(l[0])-np.array(l[1]),ord=norm)\n return (l[0],(dist,l[1]))\n\ndef calc_new_cluster(l):\n l = list(l)\n size = len(l)\n agg = sum(np.array(l))\n return tuple(agg/size)\n\ndef get_costs(init_clusters,norm):\n costs = []\n curr_clusters = init_clusters\n for i in range(max_iter): # k - means algorithm\n combos = docs.flatMap(lambda l:combine_with_cluster(l,curr_clusters)) #get (vec,clu) pairs\n combos_w_euc_dist = combos.map(lambda l:calc_dist(l,norm)) #add the distance to said cluster\n combos_w_euc_dist_grouped = combos_w_euc_dist.groupByKey()\n closest = combos_w_euc_dist_grouped.mapValues(lambda val: min(list(val))) # filter such that only the closest (dist,clust) remains as value for a vector\n costs += [sum(closest.map(lambda l:l[1][0]).collect())] #add costs for this clustering\n curr_clusters = closest.map(lambda l : (l[1][1],l[0])).groupByKey() #sort all vectors to its cluster\n new_clusters = curr_clusters.map(lambda l: calc_new_cluster(l[1])) #calculate new clusters\n curr_clusters = new_clusters.collect()\n print('Current cost is', costs[-1])\n return costs\n\n\n# In[ ]:\n\n\n#read file in\ndocs = sc.textFile('./data/data.txt').map(split)\nc1 = sc.textFile('./data/c1.txt').map(split)\nc2 = sc.textFile('./data/c2.txt').map(split)\n\n\n# In[ ]:\n\n\ncluster_rand = c1.collect()\ncluster_max = c2.collect()\n\n\n# In[ ]:\n\n\ncosts_rand = get_costs(cluster_rand,2)\n\ncosts_max = get_costs(cluster_max,2)\n\n# costs_max = []\n# curr_clusters = cluster_max\n# for i in range(max_iter): # k - means algorithm\n# combos = docs.flatMap(lambda l:combine_with_cluster(l,curr_clusters)) #get (vec,clu) pairs\n# combos_w_euc_dist = combos.map(lambda l:calc_dist(l,None)) #add the distance to said cluster\n# combos_w_euc_dist_grouped = combos_w_euc_dist.groupByKey()\n# closest = combos_w_euc_dist_grouped.mapValues(lambda val: min(list(val))) # filter such that only the closest (dist,clust) remains as value for a vector\n# costs_max += [sum(closest.map(lambda l:l[1][0]).collect())] #add costs for this clustering\n# curr_clusters = closest.map(lambda l : (l[1][1],l[0])).groupByKey() #sort all vectors to its cluster\n# new_clusters = curr_clusters.map(lambda l: calc_new_cluster(l[1])) #calculate new clusters\n# curr_clusters = new_clusters.collect()\n# print('Current cost is', costs_max[-1])\n\n\n# In[ ]:\n\n\nplt.plot(costs_rand, label = 'Random')\nplt.plot(costs_max, label= 'Max Dist')\nplt.legend()\nplt.ylabel('Cost')\nplt.xlabel('Iteration No.')\nplt.title('Cost of k-mean algo using euclidean distance')\n\n\n# In[ ]:\n\n\ncosts_rand_man = get_costs(cluster_rand,1)\ncosts_max_man = get_costs(cluster_max,1)\n\n\n# In[ ]:\n\n\nplt.plot(costs_rand_man, label = 'Random')\nplt.plot(costs_max_man, label= 'Max Dist')\nplt.legend()\nplt.ylabel('Cost')\nplt.xlabel('Iteration No.')\nplt.title('Cost of k-mean algo using manhattan distance')\n\n\n# In[ ]:\n\n\na = sc.parallelize([(\"a\",(0,(2,2))), (\"b\",(0,(3,6))), (\"c\",(3,(5,2))), (\"d\",(4,(3,1))),(\"d\",(2,(3,9))),(\"a\",(1,(3,3)))]).groupByKey()\ndef test(val):\n return min(val)\nmaxKey = a.mapValues(lambda val: min(list(val)))\nmaxKey.collect()\n\n\n# In[ ]:\n\n\na = (3,2)\nb = (3,1)\nsum(np.array([a,b]))/len([a,b])\n\n","sub_path":"HW2/q2/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"371535292","text":"from django.shortcuts import redirect,render\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom .forms import RegisterForm\n\ndef register(request):\n form_class = RegisterForm\n form = form_class(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request,f'welcome {username},your account has created successfully')\n return redirect('login')\n\n else:\n form = form_class()\n return render (request,'users/register.html',{'form':form})\n\n@login_required\ndef profilepage(request):\n return render(request,'users/profile.html')\n\n\n\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"351962198","text":"class Person:\n counter=0\n current_year=2018\n is_christmas=False\n def __init__(self, full_name, year):\n Person.counter+=1 #what will happen when you remove the \"Person.\"?\n self.id = Person.counter\n self.full_name = full_name\n self.year = year\n def __str__(self):\n return \"{}:{},{}\".format(self.id, self.full_name, self.year)\n def get_age(self):\n return Person.current_year-self.year\n def get_friendly_name(self):\n first_name = self.full_name.split()[0]\n if Person.is_christmas:\n return first_name+'\\U0001F384'\n else:\n return first_name\n\n #@classmethod<- in python2 you need @staticmethod decorator or @classmethod decorator\n def celebrate_new_year(): #you can ignore the warning.\n Person.is_christmas=True\n Person.current_year+=1\n def go_back_to_work():\n Person.is_christmas=False\n\np1 = Person('Homer Simpson', 1982) # create the first person in our program\nprint(Person.counter) # 1\nprint('{}: {}, {}'.format(p1.id, p1.full_name, p1.year)) # 1: Homer Simpson, 1982\np2 = Person('Maggie Simpson', 2017) # create the second person in our program\nprint(Person.counter) # 2\nprint('{}: {}, {}'.format(p2.id, p2.full_name, p2.year)) # 2: Maggie Simpson, 2017\np3 = Person('Burns', 0) # both the given `full_name` and `year` are invalid\nprint(Person.counter) # 3\nprint('{}: {}, {}'.format(p3.id, p3.full_name, p3.year)) # 3: Joe Bloggs, 2000\np = Person('Charles Montgomery Burns', 1937)\nprint(p.__str__()) # 1: Charles Montgomery Burns, 1937\nprint(p) # 1: Charles Montgomery Burns, 1937\nprint(Person.current_year) # 2018\nprint(Person.is_christmas) # False\nprint(p.get_age()) # 81\nprint(p.get_friendly_name()) # Charles\n# continued from above . . .\nPerson.celebrate_new_year()\nprint(Person.current_year) # 2019\nprint(Person.is_christmas) # True\nprint(p.get_age()) # 82\nprint(p.get_friendly_name()) # Charles \n\nPerson.go_back_to_work()\nprint(Person.current_year) # 2019\nprint(Person.is_christmas) # False\nprint(p.get_age()) # 82\nprint(p.get_friendly_name()) # Charles","sub_path":"Tut13/Person.py","file_name":"Person.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"314006078","text":"# © 2017 Sergio Teruel \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import _, api, fields, models\nfrom odoo.exceptions import UserError\n\n\nclass StockPickingOperationWizard(models.TransientModel):\n _name = 'stock.picking.operation.wizard'\n _description = 'Stock Picking Operation Wizard'\n\n def _prepare_default_values(self, picking):\n return {'location_dest_id': picking.location_dest_id.id}\n\n @api.model\n def default_get(self, fields):\n res = super(StockPickingOperationWizard, self).default_get(fields)\n active_model = self.env.context['active_model']\n active_ids = self.env.context['active_ids'] or []\n picking = self.env[active_model].browse(active_ids)\n res.update(self._prepare_default_values(picking))\n return res\n\n def _default_old_dest_location_id(self):\n stock_picking_obj = self.env['stock.picking']\n pickings = stock_picking_obj.browse(self.env.context['active_ids'])\n first_move_line = pickings.mapped('move_line_ids')[:1]\n return first_move_line.location_dest_id.id\n\n def _get_allowed_locations(self):\n return ['internal']\n\n def _get_allowed_location_domain(self):\n return [('usage', 'in', self._get_allowed_locations())]\n\n def _get_allowed_picking_states(self):\n return ['assigned']\n\n location_dest_id = fields.Many2one(\n comodel_name='stock.location',\n string='Actual destination location',\n required=True,\n readonly=True,\n )\n old_location_dest_id = fields.Many2one(\n comodel_name='stock.location',\n string='Old destination location',\n default=_default_old_dest_location_id,\n domain=lambda self: self._get_allowed_location_domain(),\n )\n new_location_dest_id = fields.Many2one(\n comodel_name='stock.location',\n string='New destination location',\n required=True,\n domain=lambda self: self._get_allowed_location_domain(),\n )\n change_all = fields.Boolean(\n string='Change All',\n help='Check if you want change all operations without filter '\n 'by old location')\n\n def check_allowed_pickings(self, pickings):\n forbidden_pickings = pickings.filtered(\n lambda x: x.state not in self._get_allowed_picking_states())\n if forbidden_pickings:\n raise UserError(_(\n 'You can not change operations destination location if '\n 'picking state is not in %s') % ','.join(\n self._get_allowed_picking_states()))\n pickings_with_chained_moves = pickings.filtered(\n lambda x: x.move_lines.mapped('move_dest_ids'))\n if pickings_with_chained_moves:\n raise UserError(_(\n 'You cannot change destination location if any of the moves '\n 'has a destination move.'))\n\n def action_apply(self):\n stock_picking_obj = self.env['stock.picking']\n pickings = stock_picking_obj.browse(self.env.context['active_ids'])\n self.check_allowed_pickings(pickings)\n move_lines = pickings.mapped('move_line_ids')\n\n vals = {'location_dest_id': self.new_location_dest_id.id}\n if self.change_all:\n # Write all operations destination location\n move_lines.write(vals)\n else:\n # Only write operations destination location if the location is\n # the same that old location value\n matched_op = move_lines.filtered(\n lambda x: x.location_dest_id == self.old_location_dest_id)\n matched_op.write(vals)\n return {'type': 'ir.actions.act_window_close'}\n","sub_path":"stock_picking_operation_type_location_change/wizards/stock_picking_wizard.py","file_name":"stock_picking_wizard.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"623463509","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# import required modules\nimport time\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(22,GPIO.IN,pull_up_down=GPIO.PUD_UP)\n\nwhile True:\n try: \n GPIO.wait_for_edge(22,GPIO.RISING) \n t1 = time.time()\n GPIO.wait_for_edge(22,GPIO.FALLING)\n t2=time.time()\n if((t2-t1)*170)<4:\n print(\"Zeit in s:\")\n print(t2-t1)\n print(\"Abstand in m:\")\n print((t2-t1)*170)\n \n# reset GPIO settings if user pressed Ctrl+C\n except KeyboardInterrupt:\n print(\"Measurement stopped by user\")\n GPIO.cleanup()\nGPIO.cleanup()\n\n\n","sub_path":"edge3.py","file_name":"edge3.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"431038898","text":"import threading\nfrom pprint import pprint\nimport time\nimport random\n\ncondition = threading.Condition()\n\ncontainer = []\n\ncounter = 1\n\nmore_to_come = True\n\ndef produce():\n \n global container\n global counter\n global more_to_come\n \n for i in range(5):\n \n time.sleep(random.randrange(2, 5))\n condition.acquire()\n \n item = \"News item #\" + str(counter)\n \n container.append(item)\n counter += 1\n \n print(\"\\nProduced:\", item)\n condition.notify_all()\n \n condition.release()\n \n more_to_come = False\n\ndef consume():\n \n global more_to_come\n \n while(more_to_come):\n \n condition.acquire()\n condition.wait()\n \n time.sleep(random.random())\n print(threading.current_thread().getName(), \" acquired: \", container[-1])\n \n condition.release()\n \nproducer_thread = threading.Thread(target = produce)\n\nconsumer_one_thread = threading.Thread(target=consume, name=\"News Site One\",)\nconsumer_two_thread = threading.Thread(target=consume, name=\"News Site Two\",)\nconsumer_three_thread = threading.Thread(target=consume, name=\"News Site Three\",)\n\nthreads = [producer_thread, consumer_one_thread, consumer_two_thread, consumer_three_thread,]\n\nfor t in threads:\n t.start()\n \nfor t in threads:\n t.join()\n\ntime.sleep(1)\nprint(\"\\nAll done\")\n","sub_path":"Projects/Learning/Advancded_Python/threading/ConditionSync.py","file_name":"ConditionSync.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"287293077","text":"#! python\n\nfrom math import pi\nfrom decimal import Decimal, getcontext\n\nunidade = input('Informe a unidade: ')\nraio = input('Informe o raio: ')\nraio_2 = float(raio) ** 2\n\ngetcontext().prec = 5\n\narea = (Decimal(pi)) * (Decimal(raio_2))\nprint(f'Area: {area} {unidade}')\n\nprint('Nome do módulo', __name__)\n","sub_path":"Códigos/Fundamentos/Fundamentos_projetos/area_circulo_v5.py","file_name":"area_circulo_v5.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"69509278","text":"import io\nimport pytest\n\nfrom unittest import TestCase\nfrom unittest.mock import patch\n\n\n@pytest.mark.describe('Shopping List Calculator II Tests - Outputs')\nclass TestPrint(TestCase):\n\n @pytest.mark.it('Print statements are correctly formatted')\n @patch('sys.stdout', new_callable=io.StringIO)\n def test_output(self, mock_stdout):\n from p2 import (\n total,\n tax,\n total_total,\n )\n\n stdout_list = mock_stdout.getvalue().split('\\n')\n assert stdout_list[0].strip() == f\"TOTAL: ${total}\"\n assert stdout_list[1].strip() == f\"TAX: ${tax}\"\n assert stdout_list[2].strip() == f\"TOTAL TOTAL: ${total_total}\"\n\n\n@pytest.mark.describe('Shopping List Calculator II - Variables')\nclass TestShoppingListItems(TestCase):\n\n @pytest.mark.it('`total` is the sum of item_prices')\n def test_item_total(self):\n from p1 import (\n item_price_1,\n item_price_2,\n item_price_3,\n item_price_4,\n item_price_5,\n )\n\n from p2 import total\n\n assert total == pytest.approx(item_price_1 + item_price_2 +\n item_price_3 + item_price_4 + item_price_5, 0.1)\n\n @pytest.mark.it('`tax` is `total` * `TAX_RATE`')\n def test_item_tax(self):\n from p2 import (\n total,\n TAX_RATE,\n tax\n )\n\n assert tax == pytest.approx(total * TAX_RATE * 0.01, 0.1)\n\n @pytest.mark.it('`total_total` is `total` + `tax`')\n def test_item_total_total(self):\n from p2 import (\n total,\n tax,\n total_total,\n )\n\n assert total_total == pytest.approx(total + tax, 0.1)\n","sub_path":"pset_basic_data_types/shopping_list/tests/test_p2.py","file_name":"test_p2.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"322055898","text":"from GaussianMixture import GMM\nimport pandas as pd\nimport numpy as np\nimport random\n\n# define column names\nnames = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']\n# names = ['pelvic incidence', 'pelvic tilt', 'lumbar lordosis angle', 'sacral slope',\n# 'pelvic radius', 'grade of spondylolisthesis', 'class']\n# names = ['id', 'clump_thickness', 'size_uniformity', 'shape_uniformity', 'marginal_adhesion', 'epithelial_size',\n# 'bare_nucleoli', 'bland_chromatin', 'normal_nucleoli', 'mitoses', 'class']\n\n# loading data\ndataset = pd.read_csv('iris.data.txt', names=names).values\n# dataset = pd.read_csv('column_3C.dat.txt', names=names).values\n# dataframe = pd.read_csv('breast-cancer-wisconsin.data.csv', names=names)\n# dataframe = dataframe.drop(['id', 'bare_nucleoli'], axis=1)\n# dataframe = pd.read_csv('dermatology.csv')\n# dataframe = dataframe.drop(['age'], axis=1)\n# dataset = dataframe.values\n\n# artificial dataset\n# features_1 = np.array([[random.uniform(-0.1, 0.1), random.uniform(-0.1, 0.1), 0] for _ in range(50)])\n# features_2 = np.array([[random.uniform(-0.1, 0.1), random.uniform(0.9, 1.1), 0] for _ in range(50)])\n# features_3 = np.array([[random.uniform(0.9, 1.1), random.uniform(-0.1, 0.1), 0] for _ in range(50)])\n# features_4 = np.array([[random.uniform(0.9, 1.1), random.uniform(0.9, 1.1), 1] for _ in range(50)])\n# dataset = np.concatenate([features_1, features_2, features_3, features_4], axis=0)\n\nbayesClassifier = GMM()\ndataset = bayesClassifier.normalize_dataset(dataset)\naccuracies = []\n\nfor j in range(0, 20):\n print(\"realization %d\" % j)\n train_X, train_y, test_X, test_y = bayesClassifier.train_test_split(dataset)\n\n separated_data = bayesClassifier.separate_by_class(train_X, train_y)\n model = {}\n for classValue, classData in separated_data.items():\n model[classValue] = []\n model[classValue] = (bayesClassifier.train_model(np.array(classData), 3, 50, 1))\n predictions = bayesClassifier.predict(test_X, model)\n accuracies.append(bayesClassifier.evaluate(test_y, predictions))\n print(bayesClassifier.confusion_matrix(test_y, predictions))\n bayesClassifier.plot_decision_boundaries(train_X, train_y, test_X, test_y, j)\n\nprint('accuracies: {}'.format(accuracies))\nprint('mean: {}'.format(np.mean(accuracies)))\nprint('std: {}'.format(np.std(accuracies)))\nbayesClassifier.show_plot_decision_boundaries()\n","sub_path":"MachineLearning/python-gaussianmix/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"588830538","text":"# -*- encoding: utf-8 -*-\n\n#--------------------------------------------#\n# Python 3\n#\n# Matheus Victor.\n#--------------------------------------------#\n#\n# Base de criptografia => Cifra de Cesar \n#\n#--------------------------------------------#\n\n# Imports\nimport sys\t# Pacotes de argumentos do sistema\n\n# Variáveis\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\nROT = 13\n\n# Criptografa\ndef encrypt(message):\n\tcrypt_character = ''\n\tfor character in message:\n\t\tif character in ALPHABET:\n\t\t\tcharacter_index = ALPHABET.index(character) # Verifica qual o indice em relação ao alfabeto\n\t\t\tcrypt_character += ALPHABET[(character_index + ROT) % len(ALPHABET)] # faz a rotação\n\t\telse:\n\t\t\tcrypt_character += character\n\tprint(crypt_character)\n\n# Descriptografa\ndef decrypt(message):\n\tcrypt_character = ''\n\tfor character in message:\n\t\tcharacter_index = ALPHABET.index(character) # Verifica qual o indice em relação ao alfabeto\n\t\tcrypt_character += ALPHABET[(character_index - ROT) % len(ALPHABET)] # faz a rotação\n\tprint(crypt_character)\n\n# Função principal\ndef main():\n\tcommand = sys.argv[1].lower()\n\tmessage = sys.argv[2].lower()\n\t\n\tif command == 'encrypt':\n\t\tencrypt(message)\n\telif command == 'decrypt':\n\t\tdecrypt(message)\n\nif __name__ == '__main__':\n\tmain()\n\t\n","sub_path":"Security/caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"261403677","text":"# Server Manager\n# This object is responsible for everything the server does\n# It receives and processes all client input, accepts new clients, and stores them properly\n# Also maintains all the different games, their states\n\nimport sys\nimport random\nimport time\nimport socket\nimport threading\n# our own custom libraries/modules\nfrom server.user.user import *\nfrom protocol.protocol import *\nfrom game.game import *\n\nclass Manager:\n\n def __init__(self):\n self.users = [] # list of users\n self.games = [] # list of games\n\n self.kill = False # kill switch\n \n self.idCounter = 1 # an id counter for assigning ids to clients\n self.gameCounter = 1 # a game id counter for assigning ids to games\n\n # return the next id to use\n def getId(self):\n self.idCounter += 1\n return self.idCounter - 1\n # return the next game id to use\n def getIdG(self):\n self.gameCounter += 1\n return self.gameCounter - 1\n # get user given a specific id\n def getUser(self, id):\n for user in self.users:\n if (user.id == id):\n return user\n return None\n # get user by id or name\n def getUser2(self, idname):\n idn = str(idname)\n try:\n user = self.getUser(int(idn))\n if (user != None):\n return user\n except Exception:\n 0\n for user in self.users:\n if (user.name == idname):\n return user\n return None\n # create a user with its given socket\n def createUser(self, sock):\n user = User(self)\n user.initSocket(sock)\n\n self.users.append(user)\n print(\"Accepted new client - client given ID \"+str(user.id))\n\n message = Protocol.message().setAction(Protocol.Action.SENDID) \\\n .setData(user.id) \\\n .build()\n user.send(message)\n # keeps clients alive by pinging them a message if no activity within 60 seconds\n def keepAlive(self):\n # pinging clients thread\n def pingClients():\n # ignore message to send to keep clients alive\n message = Protocol.message().setAction(Protocol.Action.IGNORE) \\\n .build()\n\n while True:\n time.sleep(0.1)\n\n if (self.kill == True): # if the server requested to exit\n break\n\n t = time.time()\n for user in self.users: # loop through users\n if (t - user.lastTouched > 60): # been 60 seconds since user has any activity\n user.send(message) # send ignore message\n user.lastTouched = t\n\n # create thread for waiting on clients\n t = threading.Timer(0.0, pingClients, () )\n t.start()\n\n # create a game\n def createGame(self, user1, user2):\n game = Game.createGame(user1.id, user1.name, user2.id, user2.name)\n self.games.append(game)\n game.id = self.getIdG()\n\n game.p1.user = user1\n user1.game = game\n game.p2.user = user2\n user2.game = game\n\n s = str(user1.id)+\",\"+user1.name+\",\"+str(user2.id)+\",\"+user2.name\n message = Protocol.message().setAction(Protocol.Action.STARTGAME) \\\n .setData(s) \\\n .build()\n user1.send(message)\n user2.send(message)\n print(\"Created game ID \"+str(game.id)+\" with players ID \"+str(user1.id)+\" and \"+str(user2.id))\n # get a game from a given game id\n def getGame(self, id):\n for game in self.games:\n if game.id == id:\n return game\n return None\n\n # removes a game\n def removeGame(self, game, endmessage=False):\n # if end message is true, let the game participants know a user was exited\n if (endmessage):\n message = Protocol.message().setAction(Protocol.Action.GAMEEND) \\\n .setData(-1) \\\n .build()\n game.sendMessage(message)\n\n game.cleanup() # request a cleanup from the users involved in the game\n self.games.remove(game) # remove the game from the list\n print(\"Game ID \"+str(game.id)+\" ended\")\n\n\n # process a message sent by a specific user\n def processMessage(self, user, message):\n # use the protocol class to turn the messages into objects we can understand\n ps = Protocol.process(message)\n if (isinstance(ps, list)):\n # if we got a list of protocol messages\n for p in ps:\n self.processProtocol(user, p, message)\n else:\n # if we just got a single protocol message\n self.processProtocol(user, ps, message)\n def processProtocol(self, user, protocol, message):\n p = protocol\n if (p.action == Protocol.Action.SETNAME):\n # client requested to set name\n user.name = p.data\n print(\"Set client \"+str(user.id)+\" name to \"+user.name)\n elif (p.action == Protocol.Action.GETPLAYERS):\n # client wants a list of players\n a = []\n for u in self.users:\n if (u.id == user.id or # user is the one requesting list of players\n u.game != None): # user is in game\n continue\n a.append(str(u.id)+\",\"+u.name)\n s = \",\".join(a)\n message = Protocol.message().setAction(Protocol.Action.RETURNPLAYERS) \\\n .setData(s) \\\n .build()\n user.send(message)\n elif (p.action == Protocol.Action.GETGAMES):\n # client requested list of games\n a = []\n for game in self.games:\n a.append(str(game.id)+\",\"+\\\n str(game.p1.id)+\",\"+str(game.p2.id))\n s = \",,\".join(a)\n message = Protocol.message().setAction(Protocol.Action.RETURNGAMES) \\\n .setData(s) \\\n .build()\n user.send(message)\n elif (p.action == Protocol.Action.REQUESTGAME):\n # client wants to start a game\n if (user.game != None): # already in a game\n return\n user2 = self.getUser2(p.data) # get the user the client wants to start a game with\n if (user2 == None):\n # user doesn't exist\n message = Protocol.message().setAction(Protocol.Action.PLAYERNOTFOUND) \\\n .build()\n user.send(message)\n return\n if (user2.game != None):\n # user is busy in a game\n message = Protocol.message().setAction(Protocol.Action.PLAYERREJECT) \\\n .build()\n user.send(message)\n return\n # we're good, start a game\n self.createGame(user, user2)\n elif (p.action == Protocol.Action.REQUESTOBSERVE):\n # client wants to begin observing a game\n if (user.game != None): # can't already be in a game\n return\n try:\n gameid = int(p.data) # this can raise an exception, if the clienet didn't enter an integer game id\n game = self.getGame(gameid)\n if game == None: # game doesn't exist, so raise an exception\n raise\n # found the game, observe it now\n game.obs.append(user) # add user to list of observers\n user.game = game\n # here we build a string consisting of the game data, its players, and its board state\n s = game.buildPlayers()\n s += \">\"\n s += game.buildState()\n s += \">\"\n message = Protocol.message().setAction(Protocol.Action.ACCEPTOBSERVE) \\\n .setData(s) \\\n .build()\n user.send(message)\n except Exception:\n # something went wrong, let the client know can't observe\n message = Protocol.message().setAction(Protocol.Action.FAILOBSERVE) \\\n .build()\n user.send(message)\n elif (p.action == Protocol.Action.ENDOBSERVE):\n # client wants to stop observing\n if user.game == None:\n return\n user.game.obs.remove(user) # remove from observer list\n user.game = None\n elif (p.action == Protocol.Action.MAKEMOVE):\n # client wants to make a move\n if (user.game == None):\n return\n game = user.game\n\n if (game.inGame(user.id)):\n # attempt to make a move with the coordinates provided\n coord = p.data.split(\",\")\n x = int(coord[0])\n y = int(coord[1])\n res = game.makeMove(user.id, x, y)\n else:\n # client is just observing\n res = \"You aren't in the game\"\n\n if (res != True):\n # if result isn't true, the move wasn't successfully made\n message = Protocol.message().setAction(Protocol.Action.BADMOVE) \\\n .setData(res) \\\n .build()\n user.send(message)\n else:\n # the move was successfully made, let players know game state was updated\n message = Protocol.message().setAction(Protocol.Action.GAMEUPDATE) \\\n .setData(str(user.id)+\",\"+p.data) \\\n .build()\n game.sendMessage(message)\n\n res = game.getResult() # get the result of the current board to see if game is over\n if (res > -1):\n # game over\n uid = 0 # draw\n if res == 1: # p1 won\n uid = game.p1.id\n if res == 2: # p2 won\n uid = game.p2.id\n message = Protocol.message().setAction(Protocol.Action.GAMEEND) \\\n .setData(uid) \\\n .build()\n game.sendMessage(message)\n # remove the game\n self.removeGame(game)\n elif (p.action == Protocol.Action.MESSAGESEND):\n # client wants to send a message to everybody in the game\n if (user.game == None):\n return\n message = Protocol.message().setAction(Protocol.Action.MESSAGEUPDATE) \\\n .setData(str(user.id)+\",\"+user.name+\",\"+p.data) \\\n .build()\n user.game.sendMessage(message, user)\n else:\n print(\"Got unknown message:\", message)\n\n # removes a user\n def removeUser(self, user):\n if (self.kill):\n return\n self.users.remove(user)\n print(\"Client \"+str(user.id)+\" disconnected\")\n # if in a game, end it\n if (user.game != None):\n if user.game.inGame(user.id): # player in game, end it\n self.removeGame(user.game, True)\n else: # just an observer\n user.game.obs.remove(user)\n\n\n # close\n def close(self):\n message = Protocol.message().setStatusCode(Protocol.Status.CLOSE) \\\n .build()\n for user in self.users[:]:\n user.send(message)\n user.sock.close()\n\n\n\n\n\n","sub_path":"tictactwo/server/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":11961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"289721840","text":"# from multiprocessing import Pool\r\n# import time\r\n\r\n# COUNT = 50000000\r\n# def countdown(n):\r\n# while n>0:\r\n# n -= 1\r\n\r\n# if __name__ == '__main__':\r\n# pool = Pool(processes=2)\r\n# start = time.time()\r\n# r1 = pool.apply_async(countdown, [COUNT//2])\r\n# r2 = pool.apply_async(countdown, [COUNT//2])\r\n# pool.close()\r\n# pool.join()\r\n# end = time.time()\r\n# print('Time taken in seconds -', end - start)\r\n\r\nimport time\r\nfrom timeit import default_timer as timer\r\nfrom multiprocessing import Pool, cpu_count\r\n\r\n\r\ndef square(n):\r\n\r\n time.sleep(2)\r\n\r\n return n * n\r\n\r\n\r\ndef main():\r\n\r\n start = timer()\r\n\r\n print(f'starting computations on {cpu_count()} cores')\r\n\r\n values = (2, 4, 6, 8)\r\n\r\n with Pool() as pool:\r\n res = pool.map(square, values)\r\n print(res)\r\n\r\n end = timer()\r\n print(f'elapsed time: {end - start}')\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"dev_test/multiprocessing_test.py","file_name":"multiprocessing_test.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"642048536","text":"from numpy import *\nfrom MoonMap import MoonMap\n\n# 任务介绍:\n# 小行星探测器在小行星上跳跃行走,目标点始终设定为原点。\n# 输入网络的地图为32*32,每像素代表4m*4m的区域,即总共128m*128m的区域\n# 为方便网络对地图的理解,设定达到原点附近的半径为8的区域就视为到达目标\n# agent-env交互方案:\n# agent接收探测器所有角点均离开地面时的状态和相应的global_map,local_map;输出期望的姿态角速度\n# env接收agent的action后,无控仿真至碰撞,然后按此时期望姿态下是否有角点在地面以下,向前或向后搜索碰前状态,\n\n\nACTION_DIM = 3\nSTATE_DIM = 16\n\n# 地图参数\nMAP_DIM = 32\nGLOBAL_PIXEL_METER = 4\nLOCAL_PIXEL_METER = 1\n\n# 小行星与探测器的相关参数\ng = array([0, 0, -0.001])\nI_star = array([[0.055, 0, 0], [0, 0.055, 0], [0, 0, 0.055]])\nI_star_inv = array([[1 / 0.055, 0, 0], [0, 1 / 0.055, 0], [0, 0, 1 / 0.055]])\nU = eye(3)\nJ_wheel = array([[0.002, 0, 0], [0, 0.002, 0], [0, 0, 0.002]])\nUJ_inv = array([[500, 0, 0], [0, 500, 0], [0, 0, 500]])\nm = 5\nl_robot = array([0.2, 0.2, 0.2])\nmu = 0.45\n# k:地面刚度数据,有待考证\nk = 4.7384 * 10 ** 4\nrecovery_co = 0.95\n# mu0:静摩擦系数\nmu0 = 0.48\nlx = l_robot[0]\nly = l_robot[1]\nlz = l_robot[2]\n# vertex_b : 体坐标系下初始各角点相对质心的位置,dim:3*8\nvertex_b = array([[lx, lx, lx, lx, -lx, -lx, -lx, -lx],\n [-ly, -ly, ly, ly, -ly, -ly, ly, ly],\n [-lz, lz, lz, -lz, -lz, lz, lz, -lz]])\nMIN_ENERGY = 0.001\nMAX_VXY = 1.5\nMAX_VZ = 0.2\n\n# RK4算法参数\nSTEP_LENGTH = 0.001\n\n\ndef wheel_model(M, w):\n flag = abs(w) >= 100\n w[flag] = 0\n M = minimum(0.1, maximum(-0.1, M))\n return M, w\n\n\n# check: OK\ndef mat_q(q):\n mq = array([[q[0], -q[1], -q[2], -q[3]],\n [q[1], q[0], -q[3], q[2]],\n [q[2], q[3], q[0], -q[1]],\n [q[3], -q[2], q[1], q[0]]])\n return mq\n\n\n# check:OK\ndef crossMatrix(w):\n wx = array([[0, -w[2], w[1]],\n [w[2], 0, -w[0]],\n [-w[1], w[0], 0]])\n return wx\n\n\n# check:OK\n# 四元数转换为姿态余弦矩阵\ndef q_to_DCM(q):\n a = q[0] * eye(3) - crossMatrix(q[1:4])\n DCM = dot(reshape(q[1:4], [-1, 1]), reshape(q[1:4], [1, -1])) + dot(a, a)\n return DCM\n\n\n# check:OK\n# 计算惯性系下的各角点参数\ndef vertex(terrain_map, state):\n XYZc, v, q, w = state[0:3], state[3:6], state[6:10], state[10:13]\n q /= sqrt(q.dot(q))\n DCM = q_to_DCM(q)\n vertex_s = dot(DCM.T, vertex_b) + reshape(XYZc, [-1, 1])\n vertex_high = vertex_s[2, :] - terrain_map.get_high(vertex_s[0, :], vertex_s[1, :])\n vertex_v = dot(DCM.T, dot(crossMatrix(w), vertex_b)) + reshape(v, [-1, 1])\n return vertex_s, vertex_high, vertex_v\n\n\n# check:OK\n# 动力学微分方程,flag标记是否发生碰撞,true为在碰撞,\ndef dynamic(terrain_map, state, M_wheel=zeros(3), flag=ones([8]) < 0, v0=zeros(8), normal=ones([3, 8])):\n XYZc, v, q, w, w_wheel = state[0:3], state[3:6], state[6:10], state[10:13], state[13:16]\n q /= sqrt(q.dot(q))\n M_wheel, w_wheel = wheel_model(M_wheel, w_wheel)\n d_w_wheel = UJ_inv.dot(M_wheel)\n F = zeros([3, 8])\n T = zeros([3, 8])\n DCM = q_to_DCM(q)\n vertex_s, vertex_high, vertex_v = vertex(terrain_map, state)\n Teq = cross(w, I_star.dot(w) + U.dot(J_wheel).dot(w_wheel)) + U.dot(J_wheel).dot(d_w_wheel)\n for j in range(0, 8):\n if flag[j]:\n r_one = vertex_b[:, j]\n high = vertex_high[j]\n normal_one = normal[:, j]\n invade_s = -dot(array([0, 0, high]), normal_one)\n if invade_s < 0:\n continue\n vertex_v_one = vertex_v[:, j]\n invade_v = -dot(vertex_v_one, normal_one)\n vt = vertex_v_one - dot(vertex_v_one, normal_one) * normal_one\n vt_value = sqrt(dot(vt, vt))\n if abs(v0[j]) < 0.00001:\n v0[j] = 0.00001 * sign(v0[j])\n c = 0.75 * (1 - recovery_co ** 2) * k * (invade_s ** 1.5) / v0[j]\n Fn_value = k * (invade_s ** 1.5) + c * invade_v\n if Fn_value < 1e-8:\n Fn_value = 1e-8\n Fn = Fn_value * normal_one\n if vt_value >= 0.0006:\n Ft = -mu * Fn_value * vt / vt_value\n else:\n # 具体方程及求解过程见 笔记\n\n A = eye(3) / m - linalg.multi_dot([crossMatrix(r_one), I_star_inv, crossMatrix(r_one), DCM])\n A_inv = linalg.inv(A)\n b = crossMatrix(r_one).dot(I_star_inv).dot(Teq) + dot(w, r_one) * w - dot(w, w) * r_one\n alpha = (Fn.dot(Fn) + A_inv.dot(b).dot(Fn)) / (A_inv.dot(Fn).dot(Fn))\n Ft = -A_inv.dot(dot(A - alpha * eye(3), Fn) + b)\n Ft_value = sqrt(Ft.dot(Ft))\n if Ft_value >= mu0 * Fn_value:\n Ft = mu0 * Fn_value * Ft / Ft_value\n F[:, j] = Ft + Fn\n T[:, j] = cross(r_one, DCM.dot(Ft + Fn))\n F = sum(F, 1) + m * g\n T = sum(T, 1)\n M_star = T - Teq\n d_XYZc = v\n d_v = F / m\n d_q = 0.5 * dot(mat_q(q), concatenate((zeros(1), w)))\n d_w = I_star_inv.dot(M_star)\n d_state = concatenate((d_XYZc, d_v, d_q, d_w, d_w_wheel))\n return d_state\n\n\n# check:OK\ndef RK4(terrain_map, t, state, step_length, M_wheel=zeros(3), flag=ones([8]) < 0, v0=zeros(8), normal=ones([3, 8])):\n h = step_length\n k1 = dynamic(terrain_map, state, M_wheel, flag, v0, normal)\n k2 = dynamic(terrain_map, state + h * k1 / 2, M_wheel, flag, v0, normal)\n k3 = dynamic(terrain_map, state + h * k2 / 2, M_wheel, flag, v0, normal)\n k4 = dynamic(terrain_map, state + h * k3, M_wheel, flag, v0, normal)\n state += h * (k1 + 2 * k2 + 2 * k3 + k4) / 6\n state[6:10] /= linalg.norm(state[6:10])\n t += h\n return t, state\n\n\nclass Env:\n s_dim = STATE_DIM\n a_dim = ACTION_DIM\n a_bound = 0.1*ones(a_dim)\n\n def __init__(self):\n self.t = 0\n self.t0 = 0\n self.state = array([0, 0, 5, 0.12, -0.08, 0, 1, 0, 0, 0, 0.2, -0.1, 0.15, -1.9, 1.5, -1.2])\n self.state0 = self.state.copy()\n self.terrain_map = MoonMap(3, MAP_DIM, GLOBAL_PIXEL_METER)\n self.map_seed = 3\n self.r_obj = MAP_DIM * GLOBAL_PIXEL_METER / 3\n\n def cut_r_obj(self):\n self.r_obj = max(self.r_obj / 3, GLOBAL_PIXEL_METER)\n\n # 生成地图\n def set_map_seed(self, sd=1):\n self.map_seed = sd\n self.terrain_map = MoonMap(sd, MAP_DIM, GLOBAL_PIXEL_METER)\n\n # check:\n # 设定初始状态,即探测器与地面的撞前状态\n # 暂时不设定难度,(根据初始xy坐标与原点(目标)的距离,分10个难度,默认为最高难度)\n def set_state_seed(self, sd=1):\n random.seed(sd)\n minXY = self.r_obj + 3 * GLOBAL_PIXEL_METER\n maxXY = MAP_DIM * GLOBAL_PIXEL_METER / 2 - 3 * GLOBAL_PIXEL_METER\n minVxy = 0.05\n maxVxy = 0.2\n XY_theta = random.random() * 2 * pi\n XY = ((maxXY - minXY) * random.random() + minXY) * array([cos(XY_theta), sin(XY_theta)])\n v_theta = random.random() * 2 * pi\n v_xy = ((maxVxy - minVxy) * random.random() + minVxy) * array([cos(v_theta), sin(v_theta)])\n vz = 0.07 * random.random() + 0.03\n q = random.rand(4)\n q /= linalg.norm(q)\n w = random.rand(3) - 0.5\n w_wheel = random.rand(3) * 2 - 1\n state_syn = concatenate([XY, zeros(1), v_xy, array([vz]), q, w, w_wheel])\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, state_syn)\n zf = -min(vertex_high) + 1e-8\n\n self.state = concatenate([XY, array([zf]), v_xy, array([vz]), q, w, w_wheel])\n self.t = 0\n self.state0 = self.state.copy()\n return self.map_seed, self.observe_state(), self.terrain_map.map_matrix, self.terrain_map.get_local_map(self.state[0:2])\n\n # check:\n # step env接收agent的action后的状态转移\n # 输入action即碰前角速度与姿态,输出新的state,reward以及标志该次仿真是否达到目的地的done,是否速度过小导致停止的stop\n # 先按假想的无控进行仿真,若探测器在空中时间小于MIN_FLY_TIME,按无控进行仿真\n # ?探测器在空中角动量守恒,应该可以计算出与action对应的飞轮转速?\n def step(self, act):\n t0 = self.t\n state0 = self.state.copy()\n flag, v0, normal = self.controlSim(act)\n pre_energy = self.energy()\n self.collisionSim(flag, v0, normal)\n after_energy = self.energy()\n loss_energy = pre_energy - after_energy\n if loss_energy <= 0:\n raise Exception(\"Energy improved!\")\n stop_bool = self.energy() < MIN_ENERGY\n over_map = (abs(self.state[0:2]) > (MAP_DIM * GLOBAL_PIXEL_METER - GLOBAL_PIXEL_METER)).any()\n over_speed = linalg.norm(self.state[3:5]) > MAX_VXY or linalg.norm(self.state[5]) > MAX_VZ\n done_bool = (abs(self.state[0:2]) < self.r_obj/2).all()\n reward_value = self.reward(done_bool, stop_bool, state0, t0, over_speed, over_map)\n return self.observe_state(), self.terrain_map.get_local_map(self.state[0:2]), reward_value, done_bool or stop_bool or over_map\n\n # check:\n # 碰撞仿真,直至所有顶点均与地面脱离\n # 更新t,state\n def collisionSim(self, flag, v0, normal):\n if not flag.any():\n raise Exception(\"Invalid collisionSim!\")\n while flag.any():\n self.t, self.state = RK4(self.terrain_map, self.t, self.state, STEP_LENGTH, zeros(3), flag, v0, normal)\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n slc1 = logical_and(flag, vertex_high > 0)\n flag[slc1] = False\n v0[slc1] = 0\n slc2 = logical_and(logical_not(flag), vertex_high <= 0)\n flag[slc2] = True\n normal[:, slc2] = self.terrain_map.get_normal(vertex_s[0, slc2], vertex_s[1, slc2])\n v0[slc2] = -sum(vertex_v[:, slc2] * normal[:, slc2], 0)\n\n # check:\n # 模拟无控仿真,直至有顶点与地面接触\n # 更新t,state,并返回进行碰撞仿真所需参数flag(碰撞标志),v0(碰撞点初始速度),normal(碰撞点初始法向量)\n # 额外返回这一段的仿真时长即探测器在空中的时间\n def controlSim(self, act):\n dw = act.copy()\n\n v0 = zeros(8)\n last_t, last_state = self.t, self.state.copy()\n flag = ones(8) < 0\n normal = ones([3, 8])\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n if (vertex_high <= 0).any():\n raise Exception(\"Invalid controlSim!\")\n # 先按0.1s的间隔仿真,找到碰撞的大致时间\n while (vertex_high > 0).all():\n last_t, last_state = self.t, self.state.copy()\n w, w_wheel = self.state[10:13], self.state[13:16]\n M_wheel = -I_star.dot(dw) - cross(w, I_star.dot(w) + U.dot(J_wheel).dot(w_wheel))\n self.t, self.state = RK4(self.terrain_map, self.t, self.state, STEP_LENGTH * 100, M_wheel)\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n # 再回到碰撞前,按0.001s的间隔仿真\n self.t, self.state = last_t, last_state.copy()\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n while (vertex_high > 0).all():\n w, w_wheel = self.state[10:13], self.state[13:16]\n M_wheel = -I_star.dot(dw) - cross(w, I_star.dot(w) + U.dot(J_wheel).dot(w_wheel))\n self.t, self.state = RK4(self.terrain_map, self.t, self.state, STEP_LENGTH, M_wheel)\n vertex_s, vertex_high, vertex_v = vertex(self.terrain_map, self.state)\n slc = vertex_high <= 0\n flag[slc] = True\n normal[:, slc] = self.terrain_map.get_normal(vertex_s[0, slc], vertex_s[1, slc])\n v0[slc] = -sum(vertex_v[:, slc] * normal[:, slc], 0)\n if (v0 < 0).any():\n raise Exception(\"Invalid v0!\")\n return flag, v0, normal\n\n # 输出强化学习的state\n def observe_state(self):\n o_s = self.state.copy()\n o_s[0:2] /= (MAP_DIM * GLOBAL_PIXEL_METER / 2)\n o_s[0:2] = minimum(maximum(o_s[0:2], -1), 1-1e-3)\n o_s[-3:] /= 200\n o_s[10:13] /= 2\n return o_s\n\n def reward(self, done_bool, stop_bool, pre_state, pre_t, over_speed, over_map):\n def _cos_vec(a, b):\n f = dot(a, b) / (linalg.norm(a) * linalg.norm(b))\n return f\n\n if done_bool:\n reward_value = 10\n elif over_map:\n reward_value = -3\n elif stop_bool:\n reward_value = (linalg.norm(self.state0[0:2]) - linalg.norm(self.state[0:2])) / \\\n max(linalg.norm(self.state0[0:2]), linalg.norm(self.state[0:2]))\n elif over_speed:\n reward_value = -2\n else:\n d = (linalg.norm(pre_state[0:2]) - linalg.norm(self.state[0:2])) / \\\n max(linalg.norm(pre_state[0:2]), linalg.norm(self.state[0:2]))\n c_pre = _cos_vec(-pre_state[0:2], pre_state[3:5])\n c = _cos_vec(-self.state[0:2], self.state[3:5])\n v_xy = linalg.norm(self.state[3:5])\n reward_value = (c - c_pre) + (v_xy*c - v_xy*sqrt(1-c**2)) + d - 0.0001 * (self.t - pre_t)\n return reward_value\n\n def energy(self):\n v, w = self.state[3:6], self.state[10:13]\n eg = 0.5*m*dot(v, v) + 0.5*reshape(w, [1, 3]).dot(I_star).dot(w)\n return eg\n\n\nif __name__ == '__main__':\n env = Env()\n env.cut_r_obj()\n env.cut_r_obj()\n for i in range(10):\n ep_reward = 0\n ave_dw = 0\n r = 0\n step = 0\n sed = random.randint(1, 10000)\n env.set_map_seed(sed)\n env.set_state_seed(sed)\n for step in range(200):\n action = random.rand(3)*env.a_bound*2 - env.a_bound\n ave_dw += linalg.norm(action)\n next_s, lm, r, done = env.step(action)\n ep_reward += r\n print(r, done)\n if done:\n break\n print(\"episode: %10d ep_reward:%10.5f last_reward:%10.5f ave_w:%10.5f\" % (\n i, ep_reward, r, ave_dw / (step + 1)))\n","sub_path":"env_plan2.py","file_name":"env_plan2.py","file_ext":"py","file_size_in_byte":14273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"130888566","text":"\"\"\"\nDatabase models of common objects\n\nauthor: officialcryptomaster@gmail.com\n\"\"\"\nfrom decimal import Decimal\nfrom enum import Enum\nfrom zero_ex.json_schemas import assert_valid\nfrom pydex_app.database import PYDEX_DB as db\nfrom pydex_app.constants import NULL_ADDRESS\nfrom pydex_app.constants import ZERO_STR, MAX_INT_STR\nfrom utils.zeroexutils import ZeroExWeb3Client\nfrom utils.miscutils import try_, now_epoch_msecs, epoch_secs_to_local_time_str, epoch_msecs_to_local_time_str\n\n\nclass OrderStatus(Enum):\n \"\"\"Enumeration of order statuses.\n Guarantees that:\n - 0 means there is no obvious problems but it may be unfundable\n - positive status means order is confirmed to be fillable\n - negative status means order is confirmed to not be fillable\n \"\"\"\n INVALID = -10 # We will probably never insert these into the database\n UNFILLABLE_UNFUNDED = -7\n UNFILLABLE_CANCELLED_PARTIALLY_FILLED = -6\n UNFILLABLE_CANCELLED = -5\n UNFILLABLE_EXPIRED_PARTIALLY_FILLED = -4\n UNFILLABLE_EXPIRED = -3\n UNFILLABLE_FILLED = -2\n UNFILLABLE = -1\n MAYBE_FILLABLE = 0\n FILLABLE = 1\n FILLABLE_FULLY = 2\n FILLABLE_PARTIALLY = 3\n\n\nclass SignedOrder(db.Model):\n \"\"\"SignedOrder model which provides persistence and convenience\n methods around dealing with 0x SignedOrder type\n \"\"\"\n hash = db.Column(db.String(42), unique=True, primary_key=True) # pylint: disable=no-member\n # ETH addresses are 40 bytes (add 2 more bytes for leading '0x')\n maker_address = db.Column(db.String(42), nullable=False) # pylint: disable=no-member\n taker_address = db.Column(db.String(42), default=NULL_ADDRESS) # pylint: disable=no-member\n exchange_address = db.Column(db.String(42), nullable=False) # pylint: disable=no-member\n fee_recipient_address = db.Column(db.String(42), default=NULL_ADDRESS) # pylint: disable=no-member\n sender_address = db.Column(db.String(42), default=NULL_ADDRESS) # pylint: disable=no-member\n # in theory, amounts can be 32 bytes, in practive, we will only allow 16 bytes\n maker_asset_amount = db.Column(db.String(32), nullable=False) # pylint: disable=no-member\n taker_asset_amount = db.Column(db.String(32), nullable=False) # pylint: disable=no-member\n # while in theory fees can be 32 bytes, in practice, we will allow 16 bytes\n maker_fee = db.Column(db.String(32), default=\"0\") # pylint: disable=no-member\n taker_fee = db.Column(db.String(32), default=\"0\") # pylint: disable=no-member\n # salt is 32 bytes or 256 bits which is at most 78 chars in decimal\n salt = db.Column(db.String(78), nullable=False) # pylint: disable=no-member\n # integer seconds since unix epoch (interpret as UTC timestamp)\n expiration_time_secs = db.Column(db.Integer, nullable=False) # pylint: disable=no-member\n # asset data for ERC20 is 36 bytes, and 68 bytes for ERC721, so that is a\n # maximum of 132 hex chars plus 2 chars for the leading '0x'\n maker_asset_data = db.Column(db.String(134), nullable=False) # pylint: disable=no-member\n taker_asset_data = db.Column(db.String(134), nullable=False) # pylint: disable=no-member\n signature = db.Column(db.String(256), nullable=False) # pylint: disable=no-member\n bid_price = db.Column(db.String(32)) # pylint: disable=no-member\n ask_price = db.Column(db.String(32)) # pylint: disable=no-member\n # integer milliseconds since unix epoch when record was created (interpret as UTC timestamp)\n created_at = db.Column(db.Integer, # pylint: disable=no-member\n nullable=False,\n default=now_epoch_msecs)\n # integer milliseconds since unix epoch since last update to record (interpret as UTC timestamp)\n last_updated_at = db.Column(db.Integer, # pylint: disable=no-member\n nullable=False,\n default=now_epoch_msecs,\n onupdate=now_epoch_msecs)\n # integer status from `OrderStatus` enum.\n order_status = db.Column(db.Integer, # pylint: disable=no-member\n index=True,\n nullable=False,\n default=OrderStatus.MAYBE_FILLABLE.value)\n # cumulative taker fill amount from order that has actually been filled\n fill_amount = db.Column(db.String(32)) # pylint: disable=no-member\n _sort_price = None # not a DB column\n\n def __str__(self):\n return (\n f\"[SignedOrder](hash={self.hash}\"\n f\" | order_status={try_(OrderStatus, self.order_status)}\"\n f\" | bid_price={self.bid_price}\"\n f\" | ask_price={self.ask_price}\"\n f\" | maker_asset_amount={self.maker_asset_amount}\"\n f\" | taker_asset_amount={self.taker_asset_amount}\"\n f\" | maker_asset_data={self.maker_asset_data}\"\n f\" | taker_asset_data={self.taker_asset_data}\"\n f\" | maker_address={self.maker_address}\"\n f\" | taker_address={self.taker_address}\"\n f\" | expires={try_(epoch_secs_to_local_time_str, self.expiration_time_secs)}\"\n f\" | create_at={try_(epoch_msecs_to_local_time_str, self.created_at)}\"\n f\" | last_updated_at={try_(epoch_msecs_to_local_time_str, self.last_updated_at)}\"\n )\n\n __repr__ = __str__\n\n def to_json(\n self,\n include_hash=False,\n include_signature=True,\n ):\n \"\"\"Get a json representation of the SignedOrder\"\"\"\n order = {\n \"makerAddress\": self.maker_address,\n \"takerAddress\": self.taker_address,\n \"makerFee\": self.maker_fee,\n \"takerFee\": self.taker_fee,\n \"senderAddress\": self.sender_address,\n \"makerAssetAmount\": self.maker_asset_amount,\n \"takerAssetAmount\": self.taker_asset_amount,\n \"makerAssetData\": self.maker_asset_data,\n \"takerAssetData\": self.taker_asset_data,\n \"exchangeAddress\": self.exchange_address,\n \"salt\": self.salt,\n \"feeRecipientAddress\": self.fee_recipient_address,\n \"expirationTimeSeconds\": self.expiration_time_secs,\n }\n if include_hash:\n if not self.hash:\n self.update_hash()\n order[\"hash\"] = self.hash\n if include_signature:\n order[\"signature\"] = self.signature\n return order\n\n def update_bid_ask_prices(self):\n \"\"\"Update the bid and ask prices and return the order for chaining\"\"\"\n self.update_bid_price()\n self.update_ask_price()\n return self\n\n def update_hash(self):\n \"\"\"Update the hash of the order and return the order for chaining\"\"\"\n self.hash = self.get_order_hash(self)\n return self\n\n def update(self):\n \"\"\"Ensure any fields that need calculation are updated\n TODO(CM): consider making use of properties to make this more convenient\n \"\"\"\n self.update_bid_ask_prices()\n self.update_hash()\n return self\n\n def update_bid_price(self, default_price=ZERO_STR):\n \"\"\"Bid price is price of taker asset per unit of maker asset\n (i.e. price of taker asset which maker is bidding to buy)\n \"\"\"\n try:\n self.bid_price = \"{:.18f}\".format(\n Decimal(self.taker_asset_amount) / Decimal(self.maker_asset_amount))\n except: # noqa E722 pylint: disable=bare-except\n self.bid_price = default_price\n return self\n\n def update_ask_price(self, default_price=MAX_INT_STR):\n \"\"\"Ask price is price of maker asset per unit of taker asset\n (i.e. price of maker asset the maker is asking to sell)\n \"\"\"\n try:\n self.ask_price = \"{:.18f}\".format(\n Decimal(self.maker_asset_amount) / Decimal(self.taker_asset_amount))\n except: # noqa E722 pylint: disable=bare-except\n self.ask_price = default_price\n return self\n\n @property\n def sort_price(self):\n \"\"\"Get a price for sorting orders\n This is useful for full set order which result in a mix of bids and asks\n (hint: make use of `set_bid_price_as_sort_price` and its equivalent\n `set_bid_price_as_sort_price`)\n \"\"\"\n return self._sort_price\n\n def set_bid_as_sort_price(self):\n \"\"\"Set the self._sort_price field to be the self.bid_price\n This can be useful for sorting full set orders\n \"\"\"\n self._sort_price = self.bid_price\n return self\n\n def set_ask_as_sort_price(self):\n \"\"\"Set the self._sort_price field to be the self.ask_price\n This can be useful for sorting full set orders\n \"\"\"\n self._sort_price = self.ask_price\n return self\n\n @classmethod\n def get_order_hash(cls, signed_order):\n \"\"\"Returns hex string hash of 0x SignedOrder object\"\"\"\n return ZeroExWeb3Client.get_order_hash(signed_order.to_json())\n\n @classmethod\n def from_json(\n cls,\n order_json,\n check_validity=False,\n include_signature=True,\n ):\n \"\"\"Given a json representation of a signed order, return a SignedOrder object\n\n Keyword arguments:\n order_json -- a dict conforming to \"/signedOrderSchema\" or \"/orderSchema\"\n (dependign on whether `include_signature` is set to True or False)\n schemas can be found at:\n \n check_validity -- whether we should do an explicit check to make sure the\n passed in dict adheres to the required schema (default: True)\n include_signature -- whether the object is expected to have the signature on it\n or not. This will affect whether \"/signedOrderSchema\" or \"/orderSchema\" is\n used for validation (default: True)\n \"\"\"\n order = cls()\n if check_validity:\n if include_signature:\n assert_valid(order_json, \"/signedOrderSchema\")\n else:\n assert_valid(order_json, \"/orderSchema\")\n order.maker_address = order_json[\"makerAddress\"]\n order.taker_address = order_json[\"takerAddress\"]\n order.maker_fee = order_json[\"makerFee\"]\n order.taker_fee = order_json[\"takerFee\"]\n order.sender_address = order_json[\"senderAddress\"]\n order.maker_asset_amount = order_json[\"makerAssetAmount\"]\n order.taker_asset_amount = order_json[\"takerAssetAmount\"]\n order.maker_asset_data = order_json[\"makerAssetData\"]\n order.taker_asset_data = order_json[\"takerAssetData\"]\n order.salt = order_json[\"salt\"]\n order.exchange_address = order_json[\"exchangeAddress\"]\n order.fee_recipient_address = order_json[\"feeRecipientAddress\"]\n order.expiration_time_secs = order_json[\"expirationTimeSeconds\"]\n if include_signature:\n order.signature = order_json[\"signature\"]\n order.update()\n return order\n","sub_path":"src/pydex_app/db_models.py","file_name":"db_models.py","file_ext":"py","file_size_in_byte":11014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"575377063","text":"# GIT utilities\nimport logging\nfrom contextlib import contextmanager\n\nfrom git import Repo\n\nlog = logging.getLogger(__name__)\n\n\ndef find_root():\n \"\"\"Based on the current directory, look for a .menhir_root.yaml file.\"\"\"\n from os.path import dirname\n from .fileutils import find_file_in_parents\n root = find_file_in_parents(\".git\")\n if root:\n return dirname(root)\n\n\ndef repo(base_dir=None):\n \"\"\"Return a repository object.\"\"\"\n base_dir = base_dir or find_root()\n return Repo(base_dir)\n\n\ndef commit(repo, commitish):\n \"\"\"Return a commit object.\"\"\"\n return repo.commit(commitish)\n\n\ndef commit_cached(repo, *args):\n \"\"\"Commit cached files.\"\"\"\n repo.git.commit(*args)\n\n\ndef head_commit(repo):\n \"\"\"Return a commit object.\"\"\"\n return repo.head.commit\n\n\ndef diff(start, end):\n \"\"\"Diff for the commit range.\"\"\"\n return diff_paths(start.diff(end))\n\n\ndef dirty_files(repo):\n return diff_paths(repo.index.diff(None))\n\n\ndef staged_files(repo):\n return diff_paths(repo.index.diff(\"HEAD\"))\n\n\ndef uncommited_files(repo):\n dirty = repo.index.diff(None)\n dirty.extend(repo.index.diff(\"HEAD\"))\n return diff_paths(dirty)\n\n\ndef unstaged_files(repo):\n dirty = repo.index.diff(None)\n dirty.extend(repo.index.diff(\"HEAD\"))\n return diff_paths(dirty)\n\n\ndef files_changed_since(repo, commitish):\n dirty = repo.index.diff(None)\n dirty.extend(repo.index.diff(commitish))\n return diff_paths(dirty)\n\n\ndef diff_paths(diff):\n rpaths = [p.a_path for p in diff.iter_change_type('R')]\n rpaths.extend([p.b_path for p in diff.iter_change_type('R')])\n\n diffs = {\n 'added': [p.b_path for p in diff.iter_change_type('A')],\n 'deleted': [p.a_path for p in diff.iter_change_type('D')],\n 'renamed': rpaths,\n 'modified': [p.b_path for p in diff.iter_change_type('M')],\n }\n all_paths = []\n for i in ['added', 'deleted', 'renamed', 'modified']:\n all_paths.extend(diffs[i])\n diffs['all'] = all_paths\n return diffs\n\n\ndef changed_files(start, end):\n from menhir import gitutils\n repo = gitutils.repo()\n start_commit = gitutils.commit(repo, start)\n end_commit = gitutils.commit(repo, end)\n changed_files = gitutils.diff(start_commit, end_commit)\n return changed_files\n\n\ndef sha(commit):\n \"\"\"Return the sha hex for a commit.\"\"\"\n return commit.hexsha\n\n\ndef branch(repo):\n \"\"\"Return the branch name.\"\"\"\n return repo.active_branch.name\n\n\n@contextmanager\ndef staged_as_committed(repo):\n staged_changes = staged_files(repo)\n log.debug('staged_changes %s', staged_changes)\n\n commit_changes = False\n if len(staged_changes['all']):\n commit_cached(repo, \"-m\", \"temp\", \"-n\")\n commit_changes = True\n\n try:\n yield\n finally:\n if commit_changes:\n repo.git.reset(\"HEAD^\", soft=True)\n\n\n@contextmanager\ndef stashed_changes(repo):\n uncommitted_changes = uncommited_files(repo)\n log.debug('uncommitted_changes %s', uncommitted_changes)\n stash_changes = False\n\n if len(uncommitted_changes['all']):\n stash_changes = True\n repo.git.stash('save', \"--quiet\", \"--include-untracked\")\n try:\n yield\n finally:\n if stash_changes:\n repo.git.stash('pop', \"--quiet\")\n","sub_path":"menhir/gitutils.py","file_name":"gitutils.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"451563226","text":"#!/usr/bin/env python3\n\n# Created by: Mr. Coxall\n# Created on: October 2019\n# This file is the B scene\n# for CircuitPython and uGame\n\nimport ugame\nimport stage\n\nimport menu_scene\n\ndef game_loop():\n # this function is a scene\n\n # an image bank for CircuitPython\n image_bank_1 = stage.Bank.from_bmp16(\"space_aliens.bmp\")\n\n # sets the background to image 0 in the bank\n # we will not change the background after initially drawing it\n background = stage.Grid(image_bank_1, 160, 120)\n\n # a list of sprites that will be updated every frame\n sprites = []\n\n # create a sprite\n # parameters (image_bank, image # in bank, x, y)\n #alien = stage.Sprite(image_bank_1, 9, 80-8, 60-8)\n #sprites.append(alien)\n\n # show text on screen\n text = stage.Text(width = 29, height = 1)\n text.move(30, 110)\n text.text(\"B\")\n\n # create a stage for the background to show up on\n # and set the frame rate to 30fps\n game = stage.Stage(ugame.display, 30)\n # set the layers, items show up in order\n game.layers = [text] + sprites + [background]\n # render the background and inital location of sprite list\n # most likely you will only render background once per scene\n game.render_block()\n\n # repeat forever, game loop\n while True:\n # get user input\n keys = ugame.buttons.get_pressed()\n\n # update game logic\n if keys & ugame.K_SELECT != 0: # Select button\n menu_scene.game_loop()\n\n\n # redraw sprite list\n game.render_sprites(sprites)\n game.tick() # wait until refresh rate finishes\n\n\nif __name__ == \"__main__\":\n game_loop()","sub_path":"b_scene.py","file_name":"b_scene.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"357503256","text":"from groundwork.patterns import GwDocumentsPattern, GwCommandsPattern\n\ncommands_content = \"\"\"\nCommands overview\n=================\n\nRegistered commands: {{app.commands.get()|count}}\n\nList of commands\n----------------\n\n {% for name, command in app.commands.get().items() %}\n * {{command.command-}}\n {% endfor %}\n\n{% for name, command in app.commands.get().items() %}\n{{command.command}}\n{{\"-\" * command.command|length}}\nName: {{command.command}}\nDescription: {{command.description}}\nPlugin: {{command.plugin.name}}\n{% endfor %}\n\n\"\"\"\n\n\nclass GwCommandsInfo(GwDocumentsPattern, GwCommandsPattern):\n \"\"\"\n Provides documents for giving an overview about registered commands.\n \"\"\"\n # GwCommandsPatterns is not really needed for this plugin as parent class, because we do not register any command.\n # However, if no plugin does inherit from GwCommandsPattern the needed argument app.commands would not exist.\n # So this is the way to make sure that command-functionality was set up when this plugins gets used.\n def __init__(self, *args, **kwargs):\n self.name = kwargs.get(\"name\", self.__class__.__name__)\n super(GwCommandsInfo, self).__init__(*args, **kwargs)\n\n def activate(self):\n self.documents.register(name=\"commands_overview\",\n content=commands_content,\n description=\"Gives an overview about all registered commands\")\n","sub_path":"groundwork/plugins/gw_commands_info.py","file_name":"gw_commands_info.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"287334560","text":"\"\"\"For assessing Calder-Verwer metric, :math:`1-(P(Y=1|S=1)-P(Y=1|S!=1))`.\"\"\"\n\nfrom ethicml.common import implements\nfrom ethicml.utility import DataTuple, Prediction\n\nfrom .metric import Metric\nfrom .prob_pos import ProbPos\n\n\nclass CV(Metric):\n \"\"\"Calder-Verwer.\"\"\"\n\n _name: str = \"CV\"\n\n @implements(Metric)\n def score(self, prediction: Prediction, actual: DataTuple) -> float:\n # has to be imported on demand because otherwise we get circular imports\n from ethicml.evaluators.per_sensitive_attribute import (\n diff_per_sensitive_attribute,\n metric_per_sensitive_attribute,\n )\n\n per_sens = metric_per_sensitive_attribute(prediction, actual, ProbPos())\n diffs = diff_per_sensitive_attribute(per_sens)\n\n return 1 - list(diffs.values())[0]\n\n @property\n def apply_per_sensitive(self) -> bool:\n \"\"\"Can this metric be applied per sensitive attribute group?\"\"\"\n return False\n\n\nclass AbsCV(CV):\n \"\"\"Absolute value of Calder-Verwer.\n\n This metric is supposed to make it easier to compare results.\n \"\"\"\n\n _name: str = \"CV absolute\"\n\n @implements(Metric)\n def score(self, prediction: Prediction, actual: DataTuple) -> float:\n cv_score = super().score(prediction, actual)\n # the following is equivalent to 1 - abs(diff)\n if cv_score > 1:\n return 2 - cv_score\n return cv_score\n","sub_path":"ethicml/metrics/cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"427085591","text":"import FWCore.ParameterSet.Config as cms\nprocess = cms.Process(\"MergeHLT\")\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 50000\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\nXXX_INPUT_XXX\n )\n)\n\nprocess.HSCPHLTDuplicate = cms.EDFilter(\"HSCPHLTFilter\",\n RemoveDuplicates = cms.bool(True),\n TriggerProcess = cms.string(\"HLT\"),\n MuonTrigger1Mask = cms.int32(1), #Activated\n PFMetTriggerMask = cms.int32(1), #Activated\n)\n\nprocess.HSCPHLTFilterPFMET = cms.EDFilter(\"HSCPHLTFilter\",\n RemoveDuplicates = cms.bool(False),\n TriggerProcess = cms.string(\"HLT\"),\n MuonTrigger1Mask = cms.int32(0), #Activated\n PFMetTriggerMask = cms.int32(1), #Activated\n)\n\nprocess.HSCPHLTFilterSingleMU = cms.EDFilter(\"HSCPHLTFilter\",\n RemoveDuplicates = cms.bool(False),\n TriggerProcess = cms.string(\"HLT\"),\n MuonTrigger1Mask = cms.int32(1), #Activated\n PFMetTriggerMask = cms.int32(0), #Activated\n)\n\nprocess.Filter = cms.Path(process.HSCPHLTDuplicate )\nprocess.HscpPathPFMet = cms.Path(process.HSCPHLTFilterPFMET )\nprocess.HscpPathSingleMu = cms.Path(process.HSCPHLTFilterSingleMU )\n\n\nprocess.Out = cms.OutputModule(\"PoolOutputModule\",\n outputCommands = cms.untracked.vstring(\n \"drop *\",\n 'keep EventAux_*_*_*',\n 'keep LumiSummary_*_*_*',\n 'keep edmMergeableCounter_*_*_*',\n \"keep *_genParticles_*_*\",\n \"keep GenEventInfoProduct_generator_*_*\",\n \"keep *_offlinePrimaryVertices_*_*\",\n #\"keep *_cscSegments_*_*\",\n #\"keep *_rpcRecHits_*_*\",\n #\"keep *_dt4DSegments_*_*\",\n \"keep SiStripClusteredmNewDetSetVector_generalTracksSkim_*_*\",\n \"keep SiPixelClusteredmNewDetSetVector_generalTracksSkim_*_*\",\n #\"keep *_reducedHSCPhbhereco_*_*\", #\n #\"keep *_reducedHSCPEcalRecHitsEB_*_*\", #\n #\"keep *_reducedHSCPEcalRecHitsEE_*_*\", #\n \"keep *_TrackRefitter_*_*\",\n \"drop TrajectorysToOnerecoTracksAssociation_TrackRefitter__\",\n \"keep *_standAloneMuons_*_*\",\n #\"drop recoTracks_standAloneMuons__*\",\n \"keep *_globalMuons_*_*\", #\n \"keep *_muonsSkim_*_*\",\n \"keep edmTriggerResults_TriggerResults_*_*\",\n \"keep recoPFJets_ak5PFJets__*\", #\n \"keep recoPFMETs_pfMet__*\", #\n \"keep recoCaloJets_ak5CaloJets__*\",\n \"keep *_HSCParticleProducer_*_*\",\n \"keep *_HSCPIsolation01__*\",\n \"keep *_HSCPIsolation03__*\",\n \"keep *_HSCPIsolation05__*\",\n \"keep *_dedx*_*_HSCPAnalysis\",\n \"keep *_muontiming_*_HSCPAnalysis\",\n \"keep triggerTriggerEvent_hltTriggerSummaryAOD_*_*\",\n \"keep PileupSummaryInfos_addPileupInfo_*_*\"\n ),\n fileName = cms.untracked.string('XXX_OUTPUT_XXX.root'),\n)\n\nprocess.endPath = cms.EndPath(process.Out)\n\nprocess.schedule = cms.Schedule(process.Filter, process.HscpPathPFMet, process.HscpPathSingleMu, process.endPath)\n\n\n","sub_path":"SUSYBSMAnalysis/HSCP/test/BuildHSCParticles/MC/Merge_cfg.py","file_name":"Merge_cfg.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"322286407","text":"import numpy as np\nnp.set_printoptions(precision=4,suppress=True)\nimport sys\nfrom functools import reduce,partial\nfrom hqca.tools import RDMFunctions as rdmf\nfrom hqca.tools import Chem as chem\nfrom hqca.tools import EnergyFunctions as enf\nfrom hqca.tools import EnergyDeterminant as end\nfrom hqca.tools import EnergyOrbital as eno\nfrom pyscf import gto,mcscf\nfrom pyscf import scf as pscf\n\n'''\n./tools/EnergyFunctions.py\n\nModule for optimizer or energy functions, i.e. for rotations, etc.\n\n'''\n\ndef find_function(\n run_type,\n spec,\n Store,\n QuantStore):\n if run_type=='noft':\n if spec=='qc':\n f = partial(\n end.energy_eval_nordm,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n if spec=='orb':\n f = partial(\n eno.energy_eval_orbitals,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n elif spec=='orb_grad':\n f = partial(\n #eno.orbital_energy_gradient_givens,\n eno.orbital_en_grad_numerical,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n if spec=='noft_grad':\n f = partial(\n end.energy_eval_grad_noft_numerical,\n **{\n 'Store':Store,\n 'QuantStore':QuantStore\n }\n )\n elif run_type=='rdm':\n f = partial(\n end.energy_eval_rdm,\n **{'Store':Store,'QuantStore':QuantStore}\n )\n return f\n\nclass Storage:\n '''\n Class for storing energetic properties -\n Basically, will store certain properties of the best 2RDM and wavefunction\n without having to return it for every function call.\n\n Also, will initiate the chemical procedure\n\n Also stores some basic properties of the molecule. However, does not hold\n properties related to the quantum optimization. Need to generate a\n QuantumStorage object to do that.\n '''\n def __init__(self,\n mol,\n Ne_as='default',\n No_as='default',\n casci=False,\n **kwargs):\n self.S = mol.intor('int1e_ovlp')\n self.T_1e = mol.intor('int1e_kin')\n self.V_1e = mol.intor('int1e_nuc')\n self.ints_1e_ao = self.V_1e+self.T_1e\n self.ints_2e_ao = mol.intor('int2e')\n try:\n self.hf = pscf.RHF(mol)\n self.hf.kernel()\n self.mol = mol\n self.hf.analyze()\n self.C= self.hf.mo_coeff\n self.f = self.hf.get_fock()\n except Exception:\n self.hf = pscf.ROHF(mol)\n self.hf.kernel()\n self.mol = mol\n self.hf.analyze()\n self.C= self.hf.mo_coeff\n self.f = self.hf.get_fock()\n if Ne_as=='default':\n self.Ne_as = mol.nelec[0]+mol.nelec[1]\n else:\n self.Ne_as = int(Ne_as)\n self.Ne_tot = mol.nelec[0]+mol.nelec[1]\n self.Ne_alp = mol.nelec[0]\n self.Ne_bet = mol.nelec[1]\n if No_as=='default':\n self.No_as = self.C.shape[0]\n else:\n self.No_as = int(No_as)\n self.No_tot = self.C.shape[0]\n if casci:\n self.mc = mcscf.CASCI(\n self.hf,\n self.No_as,\n self.Ne_as)\n self.mc.kernel()\n self.e_casci = self.mc.e_tot\n self.mc_coeff = self.mc.mo_coeff\n else:\n self.mc = None\n print('Hartree-Fock Energy: {:.8f}'.format(float(self.hf.e_tot)))\n print('CASCI Energy: {:.8f}'.format(float(self.e_casci)))\n self.E_ne = self.mol.energy_nuc()\n self.energy_best = 0\n self.energy_wf = 0\n self.energy_int = 0\n self.wf = {}\n self.rdm2=None\n self.Ci = np.linalg.inv(self.C)\n self.ints_1e =None\n self.ints_2e = None\n self.T_alpha = self.C.copy()\n self.T_beta = self.C.copy()\n self.opt_T_alpha = None\n self.opt_T_beta = None\n self.opt_done = False\n self.error = False\n self.occ_energy_calls = 0\n self.orb_energy_calls = 0\n self.active_space_calc='FCI'\n self.F_alpha = 0\n self.F_beta = 0\n self.spin = self.mol.spin\n self.kw = kwargs\n\n def gip(self):\n '''\n 'Get Initial Parameters (GIP) function.\n '''\n try:\n if self.sp=='noft':\n self.parameters=[0,0]\n elif self.sp=='rdm':\n if self.kw['spin_mapping'] in ['default','alternating']:\n Na = 1\n Nb = 1\n elif self.kw['spin_mapping']=='spin-free':\n Na = 2\n Nb = 0\n elif self.kw['spin_mapping']=='spatial':\n Na = 1\n Nb = 0\n if self.kw['entangled_pairs']=='full':\n N = 0.5*((self.No_as*Na)**2-self.No_as*Na)\n N += 0.5*((self.No_as*Nb)**2-self.No_as*Nb)\n elif self.kw['entangled_pairs']=='sequential':\n N = self.No_as-1\n elif self.kw['entangled_pairs']=='specified':\n pass\n self.parameters = [0 for i in range(int(N))]\n except AttributeError:\n print('Not assigned.')\n\n def gsm(self):\n self._generate_spin2spac_mapping()\n\n def gas(self):\n self._generate_active_space(**self.kw)\n\n def _generate_active_space(self,\n spin_mapping='default',\n **kw\n ):\n '''\n Note, all orb references are in spatial orbitals. \n '''\n self.alpha_mo={\n 'inactive':[],\n 'active':[],\n 'virtual':[],\n 'qc':[]\n }\n self.beta_mo={\n 'inactive':[],\n 'active':[],\n 'virtual':[],\n 'qc':[]\n }\n self.Ne_ia = self.Ne_tot-self.Ne_as\n self.No_ia = self.Ne_ia//2\n self.spin = spin_mapping\n self.No_v = self.No_tot-self.No_ia-self.No_as\n if self.Ne_ia%2==1:\n raise(SpinError)\n if self.Ne_ia>0:\n self.active_space_calc='CASSCF'\n ind=0\n for i in range(0,self.No_ia):\n self.alpha_mo['inactive'].append(ind)\n ind+=1\n for i in range(0,self.No_as):\n self.alpha_mo['active'].append(ind)\n ind+=1\n for i in range(0,self.No_v):\n self.alpha_mo['virtual'].append(ind)\n ind+=1\n for i in range(0,self.No_ia):\n self.beta_mo['inactive'].append(ind)\n ind+=1\n for i in range(0,self.No_as):\n self.beta_mo['active'].append(ind)\n ind+=1\n for i in range(0,self.No_v):\n self.beta_mo['virtual'].append(ind)\n ind+=1\n\n def _generate_spin2spac_mapping(self):\n self.s2s = {}\n for i in range(0,self.No_tot):\n self.s2s[i]=i\n for i in range(self.No_tot,2*self.No_tot):\n self.s2s[i]=i-self.No_tot\n\n def opt_update_wf(self,energy,wf,para):\n if energy1e-8:\n print('Error in fidelity:')\n print(self.T_alpha_old.T)\n print(self.S)\n print(self.T_alpha)\n print(self.F_alpha)\n if self.F_beta>1:\n print('Error in fidelity:')\n print(self.T_beta_old)\n print(self.S)\n print(self.T_beta.T)\n print(reduce(np.dot,(\n self.T_beta_old.T,\n self.S,\n self.T_beta)))\n print(reduce(np.dot,(\n self.T_beta_old,\n self.S,\n self.T_beta.T)))\n print(self.F_beta)\n\n\n\n def opt_update_int(self,para,energy,U_a,U_b):\n '''\n Basically, always update the energy after finding the next best step in\n an orbital optimization.\n '''\n if energy: {}'.format(k,v))\n self.Ci = np.linalg.inv(self.C)\n self.Ti_a = np.linalg.inv(self.T_alpha)\n self.Ti_b = np.linalg.inv(self.T_beta)\n Ni_a = reduce(\n np.dot, (\n self.Ti_a,self.C)\n )\n Ni_b = reduce(\n np.dot, (\n self.Ti_b,self.C)\n )\n rdm2_mo = rdmf.rotate_2rdm(\n fx.expand(self.rdm2),\n Ni_a.T,\n Ni_b.T,\n self.alpha_mo,\n self.beta_mo,\n spin2spac=self.s2s,\n region='full'\n )\n rdm1_mo = rdmf.check_2rdm(\n rdm2_mo,\n self.Ne_tot)\n print('1-RDM in the molecular orbital basis.')\n print(np.real(rdm1_mo))\n print('NO coefficients (in terms of MO):')\n print('Alpha: ')\n print(np.real(Ni_a.T))\n print('Beta: ')\n print(np.real(Ni_b.T))\n print('NO coefficients (in terms of AO):')\n print('Alpha: ')\n print(np.real(self.T_alpha))\n print('Beta: ')\n print(np.real(self.T_beta))\n sz = rdmf.Sz(\n rdm1_mo,\n self.alpha_mo,\n self.beta_mo,\n s2s=self.s2s)\n s2 = rdmf.S2(\n rdm2_mo,\n rdm1_mo,\n self.alpha_mo,\n self.beta_mo,\n s2s=self.s2s)\n print('1-RDM in the Lowdin atomic orbital basis.')\n #print('MO coefficients: ')\n rdm1_mo_a = rdm1_mo[0:self.No_tot,0:self.No_tot]\n rdm1_mo_b = rdm1_mo[self.No_tot:,self.No_tot:]\n print('Alpha:')\n print(np.real(reduce(np.dot, (self.C,rdm1_mo_a,self.Ci))))\n print('Beta:')\n print(np.real(reduce(np.dot, (self.C,rdm1_mo_b,self.Ci))))\n print('Sz value: {:.6f}'.format(np.real(sz)))\n print('S2 value: {:.6f}'.format(np.real(s2)))\n print('-- -- -- -- -- -- -- --')\n print(' -- -- -- -- -- -- --')\n\n def check(self,crit,Occ,Orb,print_run=False):\n print('Checking orbital and occupation energies for convergence...')\n if print_run:\n print('Best Energy: {}'.format(self.energy_best))\n print('Best energy from wf: {}'.format(self.energy_wf))\n print('Best energy from orbitals: {}'.format(self.energy_int))\n print('Parameters: {}'.format(self.parameters))\n print('Wavefunction: {}'.format(self.wf))\n self.energy_best = min(self.energy_wf,self.energy_int)\n if Occ.error:\n self.opt_done=True\n self.error=True\n elif Orb.error:\n self.opt_done=True\n self.error=True\n elif abs(self.energy_int-self.energy_wf) length:\n value = \"%s%s\" % (value[:length-len(ELLIPSIS)], ELLIPSIS)\n return value\n\n @staticmethod\n def get_csv_reader(url):\n try:\n resp = requests.get(url, stream=True, timeout=1, verify=True)\n except (\n requests.exceptions.ConnectionError,\n requests.exceptions.Timeout,\n requests.exceptions.TooManyRedirects\n ) as ex:\n raise serializers.ValidationError(\n dict(url=[ex.message])\n )\n except requests.exceptions.RequestException as ex:\n raise serializers.ValidationError(\n dict(url=['Unable to fetch CSV data form URL.'])\n )\n\n if resp.status_code == 404:\n raise serializers.ValidationError(\n dict(url=['The URL is not a valid CSV source.'])\n )\n\n # when using google docs URL, chunk is '' on next line. Bug?\n chunk = resp.iter_content(chunk_size=1024).next()\n\n sniffer = csv.Sniffer()\n try:\n if not chunk:\n chunk = resp.content[:1024]\n dialect = sniffer.sniff(chunk)\n except Exception:\n # Could not determine dialect\n # must investigate if we can conclude \"CSV not valid\"\n raise serializers.ValidationError(\n dict(url=['The URL is not a valid CSV source.'])\n )\n reader = csv.DictReader(\n resp.iter_lines(), dialect=dialect, fieldnames=FIELDNAMES\n )\n if sniffer.has_header(chunk):\n # skip header manually because it can be different than FIELDNAMES\n # and it wouldn't be skipped by the *reader* when iterating\n reader.next()\n return reader\n\n def create(self, validated_data):\n reader = self.get_csv_reader(validated_data['url'])\n items = []\n for row in reader:\n if row == dict(zip(FIELDNAMES, FIELDNAMES)):\n # header row was not detected by sniffer\n continue;\n else:\n # it migth happen that the sniffer would not detect a header\n # and the undetected header could be different than *fieldnames*\n # see api/tests.py::test_import_from_csv_with_unconventional_undetected_header\n\n # i don't think there's anything we could do about this here\n # since the bad header would look like a valid item row\n pass\n\n data = dict(\n user=self.context['user'].id,\n title=self.escape_and_truncate(\n row['title'] or \"N/A\", TITLE_MAX_LENGTH),\n description=self.escape_and_truncate(\n row['description'], DESCRIPTION_MAX_LENGTH),\n image=row['image'] or ''\n )\n if settings.ASYNC_IMPORT:\n Process(target=task, args=(data,)).start()\n else:\n task(data)\n return []\n\n\nclass ImageFromURLField(serializers.ImageField):\n\n def fetch(self, url):\n ser = URLSerializer(data=dict(url=url))\n\n if not ser.is_valid():\n raise ImageURLException\n\n try:\n resp = requests.get(\n ser.validated_data['url'], stream=True, timeout=1, verify=True\n )\n except requests.exceptions.RequestException:\n raise ImageURLException\n\n return resp\n\n def thumbnail(self, data):\n resp = self.fetch(data)\n try:\n im = Image.open(StringIO(resp.content))\n except IOError:\n raise ImageException\n\n im.thumbnail(THUMB_SIZE, Image.ANTIALIAS)\n out_image_data = StringIO()\n im.save(out_image_data, format=\"PNG\")\n out_image_data.seek(0)\n\n return File(out_image_data, name=\"thumbnail.png\")\n\n def to_internal_value(self, data):\n try:\n thumbnail = self.thumbnail(data)\n except (ImageURLException, ImageException):\n return None\n return super(serializers.ImageField, self).to_internal_value(thumbnail)\n\n def to_representation(self, value):\n if not value:\n return None\n serializer = URLSafeTimedSerializer(\n settings.SECRET_KEY, salt=settings.TOKEN_HASH_AUTH_SALT\n )\n auth_hash = serializer.dumps(\n self.context['request'].user.auth_token.key\n )\n return reverse(\n 'image-detail', [value.instance.id, auth_hash],\n request=self.context['request']\n )\n\nclass ItemSerializer(serializers.ModelSerializer):\n image = ImageFromURLField(required=False)\n resource_uri = serializers.HyperlinkedIdentityField(\n view_name='item-detail')\n class Meta:\n model = Item\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"333703578","text":"from datetime import datetime\nfrom flask import render_template, session, redirect, current_app, url_for, request , make_response, flash, session\nfrom . import main\nfrom .forms import BindingForm\nfrom .. import db\nfrom ..models import db, User, School\nfrom ..school import getOpener, USTB\nfrom ..wxmsgr import wxinit, todict, toxml, getwxid\n# import json\n# import urllib.request\n# from app.database import db_session\n\n@main.before_app_first_request\ndef before_first_request(): \n current_app.USTB=School('USTB')\n current_app.code=''\n\n\n# @main.teardown_request\n# def shutdown_session(exception=None):\n# db_session.remove()\n\n@main.route('/' )\ndef hello_world():\n return render_template('test.html')\n\n@main.route('/wx', methods = ['GET', 'POST'] )\ndef init_auth():\n if request.method == 'GET':\n signature = request.args[\"signature\"]\n timestamp = request.args[\"timestamp\"]\n nonce = request.args[\"nonce\"]\n echostr = request.args[\"echostr\"]\n return wxinit(signature, timestamp, nonce, echostr)\n else:\n print(request.data)\n dict = todict(request.data)\n if dict['MsgType'] == 'event' and dict['Event'] == 'CLICK' and dict[\"EventKey\"] == \"cx\":\n # url = 'http://ustbonline.coding.io' + url_for('main.grade', opid = dict['FromUserName'])\n url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3bd2eedb7bee8069&redirect_uri=http://ustbol.herokuapp.com'+ url_for('main.grade') +'&response_type=code&scope=snsapi_base#wechat_redirect' \n return toxml(dict, url)\n else:\n return 'Bad request'\n\n\n@main.route('/bd', methods = ['GET', 'POST'] )\ndef oauth():\n # session['opid']=getwxid(request.args.get(\"code\"))\n# return redirect(url_for('main.binding'))\n\n# @main.route('/binding', methods = ['GET', 'POST'])\n# def binding():\n state = None\n form = BindingForm()\n if session.get('opid'):\n opid=session['opid']\n print('session中有opid',session['opid'])\n else:\n opid=getwxid(request.args.get(\"code\"))\n session['opid'] = opid\n print('通过函数获得opid', opid)\n if form.validate_on_submit():\n ustb=USTB(form.stuid.data, form.pswd.data)\n opener = ustb.login()\n if opid and opener :\n user=User.query.filter_by(wxid=opid).first()\n if user:\n state='已重新绑定'\n else:\n user = User(opid, form.stuid.data, form.pswd.data, current_app.USTB)\n db.session.add(user)\n flash('恭喜:), 绑定成功!')\n state = '已绑定'\n else:\n flash('绑定失败:(, 请请使用微信登录,并检查学号密码是否正确')\n form.stuid.data = ''\n return render_template('binding.html', form=form, state=state)\n\n\n@main.route('/grade', methods = ['GET', 'POST'] )\ndef grade():\n if session.get('opid'):\n opid=session['opid']\n print('session中有opid',session['opid'])\n else:\n opid=getwxid(request.args.get(\"code\"))\n print('通过函数获得opid', opid)\n user = User.query.filter_by(wxid=opid).first()\n if user:\n ustb=USTB(user.stuid, user.pswd)\n opener = ustb.login()\n grade=ustb.getgrade(opener)\n return render_template('grade.html', grade=grade, lenth = len(grade))\n else:\n flash('请先绑定')\n return render_template('404.html'), 404\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"415034829","text":"\nfrom DealPackageDevKit import CompositeAttributeDefinition, CalcVal, ParseFloat\n\nclass SetCallbacksToClass(object):\n def __init__(self, inherited, base):\n self._inherited = inherited\n self._base = base\n def __enter__(self):\n self._name = self._inherited.get_name()\n self._inherited.set_name(self._base.get_name())\n def __exit__(self, type, value, traceback):\n self._inherited.set_name(self._name)\n\n\nclass OneVolVolatility(CompositeAttributeDefinition):\n def OnInit(self, quoteTradeName, callVolObjectsName, putVolObjectsName):\n self._quoteTradeName = quoteTradeName\n self._callVolObjectsName = callVolObjectsName\n self._putVolObjectsName = putVolObjectsName\n \n def Attributes(self):\n return {'volatility': CalcVal(label = 'Vol %',\n calcMapping=self.QuoteTradeName() + ':FDealSheet:Portfolio One Volatility',\n onChanged='@SimulateVolatility',\n transform='@TransformVolatility',\n solverParameter='@VolatilityParam'),\n \n 'callVolatility': CalcVal(label='@CallVolatilityLabel',\n calcMapping=self.CallVolObjectsNameName() + ':FDealSheet:Portfolio Volatility FXOStrat',\n onChanged='@ValueSimulated|UnsimulateOneVolatility',\n transform='@TransformVolatility',\n solverParameter='@VolatilityParam'),\n\n 'putVolatility': CalcVal(label='@PutVolatilityLabel',\n calcMapping=self.PutVolObjectsNameName() + ':FDealSheet:Portfolio Volatility FXOStrat',\n onChanged='@ValueSimulated|UnsimulateOneVolatility',\n transform='@TransformVolatility',\n solverParameter='@VolatilityParam')\n } if self.CallVolObjectsNameName() else {}\n '''*******************************************************\n * 1Vol get methods\n *******************************************************''' \n def QuoteTradeName(self):\n return self._quoteTradeName\n\n def CallVolObjectsNameName(self):\n return self._callVolObjectsName\n\n def PutVolObjectsNameName(self):\n return self._putVolObjectsName\n\n\nclass OneVolatility(OneVolVolatility):\n def OnInit(self, quoteTradeName, saveTradeName, altQuoteTradeName = None, saveTradeFlippedName = None, callVolObjectsName = None, putVolObjectsName = None):\n OneVolVolatility.OnInit(self, quoteTradeName, callVolObjectsName, putVolObjectsName)\n self._altQuoteTradeName = altQuoteTradeName\n self._saveTradeName = saveTradeName\n self._flippedSide = None\n if saveTradeFlippedName:\n self._flippedSide = OneVolatility( 'Flipped%s' % quoteTradeName,\n saveTradeFlippedName,\n 'Flipped%s' % altQuoteTradeName if altQuoteTradeName else '')\n self._flippedSide.set_name('flipped')\n \n def DeltaAttributes(self, callBackName, suffix = ''):\n return {'deltaBS%s'%suffix: CalcVal(label='Delta BS (1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=callBackName + ':FDealSheet:Instrument Delta One Vol FXOStrat',\n transform=self.UniqueCallback('@SolveOneVolDelta'),\n solverTopValue=True),\n\n 'deltaBS%sCall'%suffix: CalcVal(label='Delta BS Call(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=callBackName + ':FDealSheet:Instrument Delta Call One Vol FXOStrat',\n solverTopValue='solverStrike2DomPerFor'),\n\n 'deltaBS%sPut'%suffix: CalcVal(label='Delta BS Call(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=callBackName + ':FDealSheet:Instrument Delta Put One Vol FXOStrat',\n solverTopValue='solverStrikeDomPerFor')\n } if callBackName else {}\n\n def FwdDeltaAttributes(self):\n return {'fwdDeltaBS': CalcVal(label='Fwd Delta BS(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=self.SaveTradeName() + ':FDealSheet:Instrument Forward Delta One Vol FXOStrat',\n transform=self.UniqueCallback('@SolveOneVolDelta'),\n solverTopValue=True),\n\n 'fwdDeltaBSCall': CalcVal(label='Fwd Delta BS Call(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=self.SaveTradeName() + ':FDealSheet:Instrument Forward Delta Call One Vol FXOStrat',\n solverTopValue='solverStrike2DomPerFor'),\n\n 'fwdDeltaBSPut': CalcVal(label='Fwd Delta BS Put(1Vol)',\n calcConfiguration='@PriceGreekExcludeVolatilityMovement|DomesticColumnConfig',\n calcMapping=self.SaveTradeName() + ':FDealSheet:Instrument Forward Delta Put One Vol FXOStrat',\n solverTopValue='solverStrikeDomPerFor')\n }\n \n def FlippedAttributes(self):\n attrs = {}\n if self._flippedSide:\n with SetCallbacksToClass(self._flippedSide, self):\n flippedAttributes = self._flippedSide.Attributes()\n for attr, trait in flippedAttributes.items():\n attrs[self._flippedSide.PrefixedName(attr)] = trait\n return attrs\n \n def Attributes(self): \n attrs = OneVolVolatility.Attributes(self)\n attrs.update(self.DeltaAttributes(self.QuoteTradeName()))\n attrs.update(self.DeltaAttributes(self.AltQuoteTradeName(), 'Alt'))\n attrs.update(self.FwdDeltaAttributes())\n attrs.update(self.FlippedAttributes())\n return attrs\n \n \n '''*******************************************************\n * 1Vol get methods\n *******************************************************''' \n def AltQuoteTradeName(self):\n return self._altQuoteTradeName\n \n def SaveTradeName(self):\n return self._saveTradeName\n\n def SolveOneVolDelta(self, attrName, value):\n # slow solver, first creating one copy and then each solver in the loop will create an own copy of that copy\n # code should be optimized to do all solving operations in the same deal package copy\n precision = 0.0001\n maxIterations = 5\n dpCopy = self.Owner().DealPackage().Copy()\n dpCopy.SetAttribute('bidAskMode', False)\n dpCopy.Refresh()\n \n callAttr = attrName + 'Call'\n putAttr = attrName + 'Put'\n \n callSolverParam = self.Owner().GetAttributeMetaData(callAttr, 'solverTopValue')()\n putSolverParam = self.Owner().GetAttributeMetaData(putAttr, 'solverTopValue')()\n \n callValue = ParseFloat(value, formatter=dpCopy.GetAttribute(callAttr))\n \n if (dpCopy.GetAttribute(callAttr).Value().Number() > 0) != (callValue > 0):\n callValue = -callValue\n putValue = -callValue\n \n for i in range(maxIterations):\n dpCopy.SetAttribute('solverParameter', callSolverParam)\n dpCopy.SetAttribute(callAttr, callValue)\n dpCopy.SetAttribute('solverParameter', putSolverParam)\n dpCopy.SetAttribute(putAttr, putValue)\n \n if abs(dpCopy.GetAttribute(callAttr).Value().Number() - callValue) <= precision:\n break\n else:\n print (callAttr, dpCopy.GetAttribute(callAttr).Value(), putAttr, dpCopy.GetAttribute(putAttr).Value())\n raise DealPackageException(\"No solution found for '%s' that gives expected '%s' of %s. \"\n \"(Using boundary conditions precision = %f, max iterations = %d).\"\n %('strikes', attrName, value, precision, maxIterations))\n \n for attribute in ('strikeDomesticPerForeign', 'strike2DomesticPerForeign'):\n self.Owner().SetAttribute(attribute, dpCopy.GetAttribute(attribute))\n return self.Owner().GetValueToStore(attrName, dpCopy.GetAttribute(attrName).Value())\n \n","sub_path":"Extensions/PairOptionsPricerDealPackage/FPythonCode/PairOptionsOneVolatility.py","file_name":"PairOptionsOneVolatility.py","file_ext":"py","file_size_in_byte":9461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"128636144","text":"def power():\n numbers = []\n for a in range(1, 100):\n for b in range(1, 100):\n n = a ** b\n numbers.append(n)\n return numbers\n\n\ndef solve():\n summ = 0\n results = []\n for i in power():\n for j in str(i):\n summ += int(j)\n results.append(summ)\n summ = 0\n return max(results)\n\n\nprint(solve())\n","sub_path":"Problem 056.py","file_name":"Problem 056.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"131339076","text":"from django import forms\nfrom apps.administrador import models\nfrom apps.send_email import models as model_email\nfrom django.contrib.auth.models import User \nfrom django.urls import reverse_lazy\nfrom Seguimiento import settings\nfrom django.contrib.auth.hashers import make_password\nfrom django.utils.translation import ugettext_lazy as _\n\n\n#from django.db.models import Q\n#from bootstrap_datepicker.widgets import DatePicker\n#from bootstrap_datepicker_plus import DatePickerInput\n#from datetimewidget.widgets import DateTimeWidget\n\t\nclass UserForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.User\n\n\t\tfields = [\n\t\t\t'id',\n\t\t\t'password',\n\t\t\t'username',\n\t\t\t'first_name',\n\t\t\t'last_name',\n\t\t\t'email',\n\t\t\t'is_active',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id': 'Código', \n\t\t\t'password': 'Constraseña',\n\t\t\t'username': 'Cédula',\n\t\t\t'first_name': 'Nombre',\n\t\t\t'last_name': 'Apellido',\n\t\t\t'email': 'Correo',\n\t\t\t'is_active': 'Estado',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id': forms.TextInput(attrs={'class':'form-control'}),\n\t\t\t'password': forms.PasswordInput(render_value = True, \n\t\t\t\tattrs={'class':'form-control',\n\t\t\t\t }),\n\t\t\t'username': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese la cédula',\n\t\t\t\t'id' : 'username',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true', \n }),\n\t\t\t'first_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre',\n\t\t\t\t'id' : 'first_name',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n }), \n\t\t\t'last_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el apellido',\n\t\t\t\t'id' : 'last_name',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n }), \n\t\t\t'email': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el correo',\n\t\t\t\t'id' : 'email',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}), \n\t\t\t'is_active': forms.CheckboxInput(attrs={'class':'onoffswitch'}), \n\t\t\t'carrera': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(UserForm, self).__init__(*args, **kwargs)\n\t\tself.fields['email'].help_text = 'Correo institucional de la UTMACH'\n\t\tself.fields['is_active'].help_text = 'Conceder permiso para acceder al sistema'\n\t\tself.fields['password'].initial = make_password('syllabus')\n\t\tself.fields['is_active'].initial = True\n\n\tdef clean_email(self):\n\t\t#self: instancia de la clase\n\t\temail = self.cleaned_data.get(\"email\")\n\t\tif str(email) == '':\n\t\t\traise forms.ValidationError('Ingrese el correo electrónico')\n\t\telse:\n\t\t\tif not \"@\" in email:\n\t\t\t\traise forms.ValidationError('Utilice un email como: ejemplo_est@utmachala.edu.ec')\n\t\t\telse:\n\t\t\t\temail_base, extension = email.split(\"@\")\n\t\t\t\tif not \"utmachala.edu.ec\" == extension:\n\t\t\t\t\traise forms.ValidationError('Utilice un email con la extensión utmachala.edu.ec')\n\t\t\t\treturn email\n\n\tdef verificar(self, nro):\n\t\ttotal = 0\n\t\tbase = 10\n\t\td_ver = int(nro[9])# digito verificador\n\t\tmultip = (2, 1, 2, 1, 2, 1, 2, 1, 2)\n\n\t\tfor i in range(0,len(multip)):\n\t\t\tp = int(nro[i]) * multip[i]\n\t\t\tif p >= 10:\n\t\t\t\tp=p-9\n\t\t\t\ttotal+=p\n\t\t\telse:\n\t\t\t\ttotal+=p \n\t \n\t\tmod = total % base\n\t\tnuevo=total\n\t\twhile mod != 0:\n\t\t\tnuevo=nuevo+1\n\t\t\tmod = nuevo % base\n\t\td_ver= nuevo-total\n\t\treturn d_ver\n\n\tdef clean_username(self):\n\t\tusername = self.cleaned_data.get(\"username\")\n\t\tl = len(username)\n\t\tif l == 10: # verificar la longitud correcta\n\t\t\tcp = int(username[0:2])\n\t\t\tif cp >= 1 and cp <= 24: # verificar codigo de provincia de 1 a 24\n\t\t\t\ttercer_dig = int(username[2])\n\t\t\t\tif tercer_dig >= 0 and tercer_dig < 6 : # numeros entre 0 y 6\n\t\t\t\t\tif l == 10:\n\t\t\t\t\t\tif int(username[9]) == int(self.verificar(username)):\n\t\t\t\t\t\t\tif(username == '2222222222'):\n\t\t\t\t\t\t\t\traise forms.ValidationError('Cédula de identidad incorrecta')\n\t\t\t\t\t\t\t\t#print(\"Incorrecto\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\treturn username\n\t\t\t\t\t\t\t\t#print(\"Cedula correcta\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise forms.ValidationError('Cédula de identidad incorrecta')\n\t\t\t\t\t\t\t#print(\"Cedula erronea\")\n\t\t\t\telse:\n\t\t\t\t\traise forms.ValidationError('Tercer digito invalido')\n\t\t\t\t\t#print('Tercer digito invalido')\n\t\t\telse:\n\t\t\t\traise forms.ValidationError('Cédula de provincia incorrecto')\n\t\t\t\t#print('Codigo de provincia incorrecto') \n\t\telse:\n\t\t\traise forms.ValidationError('Cédula de identidad incorrecta, debe tener 10 dígitos')\n\t\t\t#print('Longitud incorrecta del numero ingresado')\n\n\t# def clean_password(self):\n\t# \tclave = self.cleaned_data.get('password')\n\t# \tprint(clave)\n\t# \tclave = make_password(clave)\n\t# \tprint(clave)\n\t# \treturn clave\n\nclass EstudianteForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.User\n\n\t\tfields = [\n\t\t\t'username',\n\t\t\t'first_name',\n\t\t\t'last_name',\n\t\t\t'email',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'username': 'Cédula',\n\t\t\t'first_name': 'Nombre',\n\t\t\t'last_name': 'Apellido',\n\t\t\t'email': 'Correo',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'username': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese la cédula' }),\n\t\t\t'first_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}), # muestra la lista de carreras\n\t\t\t'last_name': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el apellido',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}), \n\t\t\t'email': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el correo'}), \n\t\t\t'carrera': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(EstudianteForm, self).__init__(*args, **kwargs)\n\t\tself.fields['email'].help_text = 'Correo institucional de la UTMACH'\n\t\tself.fields['username'].required = True\n\t\tself.fields['first_name'].required = True\n\t\tself.fields['last_name'].required = True\n\t\tself.fields['email'].required = True\n\t\tself.fields['carrera'].required = False\n\n\tdef clean_email(self):\n\t\t#self: instancia de la clase\n\t\temail = self.cleaned_data.get(\"email\")\n\t\tif str(email) == '':\n\t\t\traise forms.ValidationError('Ingrese el correo electrónico')\n\t\telse:\n\t\t\tif not \"@\" in email:\n\t\t\t\traise forms.ValidationError('Utilice un email como: ejemplo_est@utmachala.edu.ec')\n\t\t\telse:\n\t\t\t\temail_base, extension = email.split(\"@\")\n\t\t\t\tif not \"utmachala.edu.ec\" == extension:\n\t\t\t\t\traise forms.ValidationError('Utilice un email con la extensión utmachala.edu.ec')\n\t\t\t\treturn email\n\nclass CarreraForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Carrera\n\n\t\tfields = [\n\t\t\t'id_carrera',\n\t\t\t'nombre_carrera',\n\t\t]\n\t\tlabels = {\n\t\t\t'id_carrera': 'Código' ,\n\t\t\t'nombre_carrera': 'Carrera',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_carrera': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_carrera',\n }),\n\t\t\t'nombre_carrera': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese la carrera',\n\t\t\t\t'id' : 'nombre_carrera',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n }),\n\t\t}\n\nclass EnviarCorreoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = model_email.Mensajes\n\n\t\tfields = [\n\t\t\t'id_mensaje',\n\t\t\t'asunto',\n\t\t\t'mensaje',\n\t\t\t'remitente',\n\t\t\t'destinatario',\n\t\t]\n\t\tlabels = {\n\t\t\t'id_mensaje': 'Código',\n\t\t\t'asunto': 'Asunto',\n\t\t\t'mensaje': 'Mensaje',\n\t\t\t'remitente': 'Remitente',\n\t\t\t'destinatario': 'Destinatario',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_mensaje': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_mensaje',\n }),\n\t\t\t'asunto': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el asunto',\n\t\t\t\t'id': 'asunto',\n 'autocomplete': 'off',\n 'required': 'true',\n }),\n\t\t\t'mensaje': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el mensaje',\n\t\t\t\t'id': 'mensaje',\n 'autocomplete': 'off',\n 'required': 'true',\n }),\n\t\t\t'remitente': forms.Select(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el correo',\n\t\t\t\t'id': 'remitente',\n 'autocomplete': 'off',\n }),\n\t\t\t'destinatario': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el destinatario',\n\t\t\t\t'id': 'destinatario',\n 'autocomplete': 'off',\n 'required': 'true',\n }),\n\t\t}\n\nclass PeriodosForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Periodo\t\n\n\t\tfields = [\n\t\t\t'id_periodo',\n\t\t\t'estado_periodo',\n\t\t\t'fecha_inicio',\n\t\t\t'fecha_fin',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_periodo': 'Periodo' ,\n\t\t\t'estado_periodo': 'Estado',\n\t\t\t'fecha_inicio': 'Fecha de inicio',\n\t\t\t'fecha_fin': 'Fecha fin',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_periodo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_periodo',\n\t\t\t\t'onkeypress': 'return eliminarEspaciosVacios(event);', \n 'autocomplete' : 'off',\n 'required' : 'true',\n }),\n\t\t\t'estado_periodo': forms.CheckboxInput(),\n\t\t\t'fecha_inicio': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t\t'fecha_fin': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(PeriodosForm, self).__init__(*args,**kwargs)\n\t\tself.fields['estado_periodo'].initial = True\n\n\t#usar el metodo clean para otro tipo de validaciones\n\tdef clean(self):\n\t\tfecha_inicio = self.cleaned_data.get('fecha_inicio')\n\t\tfecha_fin = self.cleaned_data.get('fecha_fin')\n\t\tperiodo = self.cleaned_data.get('id_periodo')\n\n\t\tfecha_inicio_valida = False\n\t\tfecha_fin_valida = False\n\n\t\tif fecha_inicio is not None:\n\t\t\tfecha_inicio_valida = True\t\t\t\n\n\t\tif fecha_fin is not None:\n\t\t\tfecha_fin_valida = True\n\n\t\tif fecha_inicio_valida == False and fecha_fin_valida == False:\n\t\t\traise forms.ValidationError('Ingrese la fecha de inicio y fin del periodo')\n\t\telse:\n\t\t\tif fecha_inicio_valida == False:\n\t\t\t\traise forms.ValidationError('Ingrese una fecha de inicio')\n\t\t\telif fecha_fin_valida == False:\n\t\t\t\traise forms.ValidationError('Ingrese una fecha de cierre')\t\n\t\t\telse:\n\t\t\t\tfecha_inicio = str(fecha_inicio)\n\t\t\t\tfecha_fin = str(fecha_fin)\n\n\t\t\t\tanio_inicio, mes_inicio, dia_inicio = str(fecha_inicio).split(\"-\")\n\t\t\t\tanio_fin, mes_fin, dia_fin = str(fecha_fin).split(\"-\")\n\n\t\t\t\tdia_inicio = int(dia_inicio)\n\t\t\t\tmes_inicio = int (mes_inicio)\n\t\t\t\tanio_inicio = int(anio_inicio)\n\n\t\t\t\tdia_fin = int(dia_fin)\n\t\t\t\tmes_fin = int(mes_fin)\n\t\t\t\tanio_fin = int(anio_fin)\n\n\t\t\t\tif anio_inicio < anio_fin:\n\t\t\t\t\t#fechas_validadas = True\n\t\t\t\t\treturn super(PeriodosForm,self).clean()\n\t\t\t\telif anio_inicio == anio_fin:\n\t\t\t\t\tif mes_inicio < mes_fin:\n\t\t\t\t\t\t#fechas_validadas = True\n\t\t\t\t\t\treturn super(PeriodosForm,self).clean()\n\t\t\t\t\telif mes_inicio == mes_fin:\n\t\t\t\t\t\tif dia_inicio <= dia_fin:\n\t\t\t\t\t\t\t#fechas_validadas = True\n\t\t\t\t\t\t\treturn super(PeriodosForm,self).clean()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise forms.ValidationError('Fecha de inicio mayor a fecha de cierre')\n\t\t\t\t\telse:\n\t\t\t\t\t\traise forms.ValidationError('Fecha de inicio mayor a fecha de cierre')\t\n\t\t\t\telse:\n\t\t\t\t\traise forms.ValidationError('Fecha de inicio mayor a fecha de cierre')\n\n\n\t#validacion estado \n\tdef clean_estado_periodo(self):\n\t\t#self: instancia de la clase\n\t\testado = self.cleaned_data.get('estado_periodo')\n\t\tcodigo_periodo = self.cleaned_data.get('id_periodo')\n\n\t\tnumero_periodos_activos = len(models.Periodo.objects.filter(estado_periodo =True))\n\t\t#print('numero de periodos activos '+str(numero_periodos_activos))\n\n\t\tif estado == False:\n\t\t\treturn estado\n\t\telse: #estado activo\n\t\t\tif numero_periodos_activos > 0:\n\t\t\t\tfilas = len(models.Periodo.objects.filter(id_periodo = codigo_periodo, estado_periodo = True))\n\t\t\t\tif str(filas) == '1': \n\t\t\t\t\treturn estado\n\t\t\t\telse:\n\t\t\t\t\t#Si estoy agregando un periodo con estado activo, y hay ya un periodo activo, no se debe guardar ese registro\n\t\t\t\t\traise forms.ValidationError('Desactive el periodo que se encuentra activo')\t\t\t\n\t\t\telif numero_periodos_activos == 0:\n\t\t\t\t#Si estoy agregando un periodo con estado activo, y no hay ningun periodo activo, se debe guardar ese registro\n\t\t\t\treturn estado\n\t\t\treturn estado\n\nclass CursoNuevoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Curso\n\n\t\tfields = [\n\t\t\t'id_curso',\n\t\t\t'nombre_curso',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso': 'Código' ,\n\t\t\t'nombre_curso': 'Curso',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_curso',\n\t\t\t\t}),\n\t\t\t'nombre_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el curso',\n\t\t\t\t'id' : 'nombre_curso',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}), \n\t\t\t'carrera': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t}\n\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcarrera = kwargs.pop('carrera')\n\t\tsuper(CursoNuevoForm, self).__init__(*args,**kwargs)\n\t\tself.fields['carrera'].initial = carrera\n\n\nclass CursoEditarForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Curso\n\n\t\tfields = [\n\t\t\t'id_curso',\n\t\t\t'nombre_curso',\n\t\t\t'carrera',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso': 'Código' ,\n\t\t\t'nombre_curso': 'Curso',\n\t\t\t'carrera': 'Carrera',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'nombre_curso': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el curso',\n\t\t\t\t'id' : 'nombre_curso',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}), \n\t\t\t'carrera': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t}\n\n\nclass CursoParaleloForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Cursos_Paralelo\n\n\t\tfields = [\n\t\t\t'id_curso_paralelo',\n\t\t\t'curso',\n\t\t\t'paralelo',\n\t\t\t'estudiante',\n\t\t\t'periodo',\n\t\t\t'estado_curso_paralelo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso_paralelo': 'Código' ,\n\t\t\t'curso': 'Curso',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'estado_curso_paralelo': 'Estado',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso_paralelo': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'curso': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'curso',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), # muestra la lista de cursos\n\t\t\t'paralelo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t'id' : 'paralelo',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t}), # muestra la lista de paralelos \n\t\t\t'estudiante': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'periodo',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'estado_curso_paralelo': forms.CheckboxInput(attrs={'class':'onoffswitch'}),\n\t\t}\n\t\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(CursoParaleloForm, self).__init__(*args,**kwargs)\n\t\tperiodo_actual = models.Periodo.objects.get(estado_periodo = True)\n\t\tself.fields['estudiante'].required = False\n\t\tself.fields['periodo'].initial = periodo_actual\n\t\tself.fields['estado_curso_paralelo'].initial = True \n\t\tself.fields['curso'].queryset = models.Curso.objects.all().order_by('carrera', 'id_curso') \n\n\t#validacion de los campos de CursoParalelo \n\tdef clean(self):\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\testado = self.cleaned_data.get('estado_curso_paralelo')\n\n\t\tcantidad_curso_paralelo = len(models.Cursos_Paralelo.objects.filter(curso = curso, paralelo = paralelo, periodo = periodo))\n\t\tif cantidad_curso_paralelo == 0:\n\t\t\treturn super(CursoParaleloForm,self).clean()\n\t\telse:\n\t\t\traise forms.ValidationError(str(curso) + ' ' + str(paralelo) + ' ya ha sido creado en el periodo ' + str(periodo) )\n\n\nclass CursoParaleloFormEdit(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Cursos_Paralelo\n\n\t\tfields = [\n\t\t\t'id_curso_paralelo',\n\t\t\t'curso',\n\t\t\t'paralelo',\n\t\t\t'estudiante',\n\t\t\t'periodo',\n\t\t\t'estado_curso_paralelo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_curso_paralelo': 'Código' ,\n\t\t\t'curso': 'Curso',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'estado_curso_paralelo': 'Estado', \n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_curso_paralelo': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'curso': forms.HiddenInput(attrs={'class':'form-control'}), # muestra la lista de cursos\n\t\t\t'paralelo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}), # muestra la lista de paralelos \n\t\t\t'estudiante': forms.Select(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t\t'estado_curso_paralelo': forms.CheckboxInput(attrs={'class':'onoffswitch'}),\n\t\t}\n\t\n\tdef __init__(self, *args, **kwargs):\n\t\tcarrera = kwargs.pop('carrera')\n\t\tsuper(CursoParaleloFormEdit, self).__init__(*args,**kwargs)\n\t\tperiodo = models.Periodo.objects.get(estado_periodo = True)\n\t\tself.fields['estado_curso_paralelo'].help_text = 'Marque esta opción si aún el estudiante está a cargo de este curso'\n\t\tself.fields['estudiante'].queryset = models.User.objects.filter(is_superuser=False, is_active = True, carrera = carrera)\n\t\tself.fields['estudiante'].required = True\n\t\tself.fields['curso'].required = True\n\t\tself.fields['periodo'].required = True\n\t\tself.fields['paralelo'].required = False\n\t\tself.fields['periodo'].initial = periodo\n\n\t#validacion de los campos de CursoParalelo \n\tdef clean(self):\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\testudiante = self.cleaned_data.get('estudiante')\n\t\testado = self.cleaned_data.get('estado_curso_paralelo')\n\n\t\tif (estado == False):\n\t\t\treturn super(CursoParaleloFormEdit,self).clean()\n\t\telse:\n\t\t\tcantidad_curso_paralelo = len(models.Cursos_Paralelo.objects.filter(estudiante = estudiante, estado_curso_paralelo = True, periodo = periodo, curso=curso, paralelo=paralelo))\n\n\t\t\tif cantidad_curso_paralelo == 0:\n\t\t\t\tcantidad_curso_paralelo = len(models.Cursos_Paralelo.objects.filter(estudiante = estudiante, estado_curso_paralelo = True, periodo = periodo))\n\t\t\t\tif cantidad_curso_paralelo == 0:\n\t\t\t\t\treturn super(CursoParaleloFormEdit,self).clean()\n\t\t\t\telse:\t\t\t\t\t\n\t\t\t\t\traise forms.ValidationError(str(estudiante) + \" ya tiene asignado un curso en el periodo \" +str(periodo))\n\t\t\telse:\n\t\t\t\traise forms.ValidationError(str(estudiante) + \" ya tiene asignado un curso en el periodo \" +str(periodo))\n\n\nclass DocenteForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Docente\n\n\t\tfields = [\n\t\t\t'id_docente',\n\t\t\t'nombre_docente',\n\t\t\t'apellido_docente',\n\t\t\t'estado_docente',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_docente': 'Cédula',\n\t\t\t'nombre_docente': 'Nombre',\n\t\t\t'apellido_docente': 'Apellido',\n\t\t\t'correo_docente': 'Correo',\n\t\t\t'estado_docente': 'Estado',\n\t\t\t'telefono_docente': 'Telefono',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_docente': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n }),\n\t\t\t'nombre_docente': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el nombre',\n\t\t\t\t'id' : 'nombre_docente',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',}),\n\t\t\t'apellido_docente': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el apellido',\n\t\t\t\t'id' : 'apellido_docente',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}),\n\t\t\t'estado_docente': forms.CheckboxInput(),\n\t\t}\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(DocenteForm, self).__init__(*args, **kwargs)\n\t\tself.fields['estado_docente'].initial = True\n\t\t#self.fields['nombre_docente'].error_messages = {'required': 'First Name is Required'}\n\n\nclass AsignaturaForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Asignatura\n\n\t\tfields = [\n\t\t\t'id_asignatura',\n\t\t\t'nombre_asignatura',\n\t\t\t'nro_creditos',\n\t\t\t'carrera',\n\t\t\t'curso',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_asignatura': 'Código',\n\t\t\t'nombre_asignatura': 'Asignatura',\n\t\t\t'nro_creditos': 'Número de créditos',\n\t\t\t'carrera': 'Carrera',\n\t\t\t'curso': 'Curso',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_asignatura',\n\t\t\t\t'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}),\n\t\t\t'nombre_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre de la asignatura',\n\t\t\t\t'id' : 'nombre_asignatura',\n 'onkeypress' : 'return soloLetras(event);',\n 'onKeyUp' : 'return convertirMayuscula(this);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n\t\t\t\t}),\n\t\t\t'nro_creditos': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el número de créditos',\n\t\t\t\t'id' : 'nro_creditos',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\n\t\t\t'carrera': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), # muestra la lista de carreras\n\t\t\t'curso': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t'id' : 'id_curso',\n\t\t\t\t}), # muestra la lista de cursos\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcurso = kwargs.pop('curso')\n\t\tsuper(AsignaturaForm, self).__init__(*args,**kwargs)\n\t\tself.fields['curso'].initial = curso\n\t\tcurso = models.Curso.objects.filter(id_curso=curso)\n\t\tcarrera = 0\n\t\tfor row in curso:\n\t\t\tcarrera = int(row.carrera_id)\n\n\t\tself.fields['carrera'].initial = carrera\n\n\tdef clean(self):\n\t\tmateria = self.cleaned_data.get(\"nombre_asignatura\")\n\t\tcurso = self.cleaned_data.get(\"curso\")\n\t\tcarrera = self.cleaned_data.get(\"carrera\")\n\t\tcantidad_filas = len(models.Asignatura.objects.filter(nombre_asignatura = materia, curso = curso, carrera = carrera))\n\n\t\tnro_creditos = self.cleaned_data.get(\"nro_creditos\")\n\t\tif nro_creditos <= 0:\n\t\t\traise forms.ValidationError('El número de créditos debe ser mayor a cero')\n\t\telse:\n\t\t\tif cantidad_filas == 0:\n\t\t\t\treturn super(AsignaturaForm,self).clean()\n\t\t\telse:\n\t\t\t\traise forms.ValidationError(\"Ya se ha registrado \" + str(materia) + \" en \" + str(curso) )\n\n\nclass AsignaturaEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Asignatura\n\n\t\tfields = [\n\t\t\t'id_asignatura',\n\t\t\t'nombre_asignatura',\n\t\t\t'nro_creditos',\n\t\t\t'carrera',\n\t\t\t'curso',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_asignatura': 'Código',\n\t\t\t'nombre_asignatura': 'Asignatura',\n\t\t\t'nro_creditos': 'Número de créditos',\n\t\t\t'carrera': 'Carrera',\n\t\t\t'curso': 'Curso',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_asignatura': forms.HiddenInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'nombre_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el nombre de la asignatura',\n\t\t\t\t'onkeypress' : 'return soloLetras(event);',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}),\n\t\t\t'nro_creditos': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el número de créditos',\n\t\t\t\t'onkeypress' : 'return soloNumeros(event);',\n\t\t\t\t'type':'number',\n\t\t\t\t}),\n\t\t\t'carrera': forms.HiddenInput(attrs={'class':'form-control'}), # muestra la lista de carreras\n\t\t\t'curso': forms.HiddenInput(attrs={'class':'form-control'}), # muestra la lista de cursos\n\t\t}\n\n\tdef clean(self):\n\t\tnro_creditos = self.cleaned_data.get(\"nro_creditos\")\n\t\tif nro_creditos <= 0:\n\t\t\traise forms.ValidationError('El número de créditos debe ser mayor a cero')\n\t\telse:\n\t\t\treturn super(AsignaturaEditForm,self).clean()\n\nclass AsignaturaDocenteForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Docentes_Asignatura\n\n\t\tfields = [\n\t\t\t'id_docente_asignatura',\n\t\t\t'curso',\n\t\t\t'asignatura',\n\t\t\t'paralelo',\n\t\t\t'docente',\n\t\t\t'periodo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_docente_asignatura': 'Código',\n\t\t\t'curso': 'Curso',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'docente': 'Docente',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_docente_asignatura': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_docente_asignatura',\n\t\t\t\t}),\n\t\t\t'curso': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t}),\n\t\t\t'asignatura': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), \n\t\t\t'paralelo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t}),\n\t\t\t'periodo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t}),\n\t\t\t'docente': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t'id' : 'docente',\n\t\t\t\t}),\t\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tparalelo = kwargs.pop('paralelo')\n\t\tcurso = kwargs.pop('curso')\n\t\tperiodo = kwargs.pop('periodo')\n\t\tsuper(AsignaturaDocenteForm, self).__init__(*args, **kwargs)\n\t\tself.fields['docente'].queryset = models.Docente.objects.filter(estado_docente = True).order_by('apellido_docente')\n\t\tself.fields['asignatura'].queryset = models.Asignatura.objects.filter(curso = curso)\n\t\tself.fields['periodo'].initial = periodo\n\t\tself.fields['paralelo'].initial = paralelo\n\t\tself.fields['curso'].initial = curso\n\n\t#validacion de los campos de Asignaturas Docentes \n\tdef clean(self): #self: instancia de la clase\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\tdocente = self.cleaned_data.get('docente')\n\t\tasignatura = self.cleaned_data.get('asignatura')\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\n\t\tif docente == None or asignatura == None or paralelo == '' or curso == None:\n\t\t\traise forms.ValidationError(\"Completa todos los campos\")\n\n\n\t\tcantidad_estudiantes = len(models.Docentes_Asignatura.objects.filter(periodo = periodo, asignatura = asignatura, curso = curso, docente = docente, paralelo = paralelo))\n\t\tif cantidad_estudiantes == 0:\n\t\t\tcantidad_estudiantes = len(models.Docentes_Asignatura.objects.filter(periodo = periodo, asignatura = asignatura, curso = curso, paralelo = paralelo))\n\t\t\tif cantidad_estudiantes == 0:\n\t\t\t\treturn super(AsignaturaDocenteForm,self).clean()\n\t\t\telse:\n\t\t\t\traise forms.ValidationError(\"Ya existe un docente asignado a dictar clases de \" + str(asignatura) + \" en \" + str(curso) + str(paralelo) + \" durante el periodo \" + str(periodo))\n\t\telse:\t\n\t\t\traise forms.ValidationError( str(docente) + \" ya tiene asignado \" + str(curso) + \" \" + str(paralelo) + \" y la asignatura de \" + str(asignatura) + \" en el periodo \" +str(periodo))\n\n\nclass AsignaturaDocenteEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Docentes_Asignatura\n\t\tfields = [\n\t\t\t'id_docente_asignatura',\n\t\t\t'curso',\n\t\t\t'asignatura',\n\t\t\t'paralelo',\n\t\t\t'docente',\n\t\t\t'periodo',\n\t\t]\n\n\t\tlabels = {\n\t\t\t'id_docente_asignatura': 'Código',\n\t\t\t'curso': 'Curso',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'paralelo': 'Paralelo',\n\t\t\t'docente': 'Docente',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\n\t\twidgets = {\n\t\t\t'id_docente_asignatura': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t'curso': forms.Select(attrs={'class':'form-control'}),\n\t\t\t'asignatura': forms.Select(attrs={'class':'form-control'}), \n\t\t\t'paralelo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el paralelo',\n\t\t\t\t'onKeyUp' : 'return convertirMayuscula(this);',\n\t\t\t\t}),\n\t\t\t'periodo': forms.TextInput(attrs={'class':'form-control'}),\n\t\t\t'docente': forms.Select(attrs={'class':'form-control'}),\t\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tasignatura_docente = kwargs.pop('asignatura_docente')\n\t\tasignatura_docente = models.Docentes_Asignatura.objects.get(id_docente_asignatura = asignatura_docente)\n\n\t\tsuper(AsignaturaDocenteEditForm, self).__init__(*args, **kwargs)\n\t\tself.fields['docente'].queryset = models.Docente.objects.filter(estado_docente = True)\n\t\tself.fields['periodo'].initial = asignatura_docente.periodo\n\t\tself.fields['curso'].initial = asignatura_docente.curso\n\t\tself.fields['paralelo'].initial = asignatura_docente.paralelo\n\t\tself.fields['asignatura'].initial = asignatura_docente.asignatura\n\n\t#validacion de los campos de Asignaturas Docentes \n\tdef clean(self):\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\tdocente = self.cleaned_data.get('docente')\n\t\tasignatura = self.cleaned_data.get('asignatura')\n\t\tcurso = self.cleaned_data.get('curso')\n\t\tparalelo = self.cleaned_data.get('paralelo')\n\n\t\tif docente == None or asignatura == None:\n\t\t\tif docente == None and asignatura == None:\n\t\t\t\traise forms.ValidationError(\"Completa los campos de docente, asignatura y paralelo\")\n\t\t\telse:\n\t\t\t\tif docente == None:\n\t\t\t\t\traise forms.ValidationError(\"Completa el campo de docente\")\n\t\t\t\telse:\n\t\t\t\t\tif asignatura==None:\n\t\t\t\t\t\traise forms.ValidationError(\"Completa el campo de asignatura\")\t\t\t\n\n\t\tcantidad_docentes_asignaturas = len(models.Docentes_Asignatura.objects.filter(periodo = periodo, asignatura = asignatura, curso = curso, docente = docente, paralelo = paralelo))\n\t\tif cantidad_docentes_asignaturas == 0:\n\t\t\treturn super(AsignaturaDocenteEditForm,self).clean()\n\t\telse:\t\n\t\t\t#return super(AsignaturaDocenteEditForm,self).clean()\n\t\t\traise forms.ValidationError(str(docente) + \" ya tiene a cargo \" + str(asignatura) + \" en el periodo \" +str(periodo))\n\nclass HorarioForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Horario\t\n\t\tfields = [\n\t\t\t'id_horario',\n\t\t\t'curso_paralelo',\n\t\t\t'asignatura',\n\t\t\t'dia',\n\t\t\t'hora',\t\t\n\t\t\t'periodo',\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_horario': 'Horario' ,\n\t\t\t'curso_paralelo': 'Curso - Paralelo',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'dia': 'Día',\n\t\t\t'hora': 'Número de horas',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_horario': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_horario',\n\t\t\t\t}),\n\t\t\t'curso_paralelo': forms.HiddenInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'asignatura': forms.Select(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'dia': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'dia',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), \n\t\t\t'hora': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el número de horas',\n\t\t\t\t'id' : 'hora',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\t\t\n\t\t\t'periodo': forms.HiddenInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcurso_paralelo = kwargs.pop('curso_paralelo')\n\t\tcurso = kwargs.pop('curso')\n\t\tperiodo = kwargs.pop('periodo')\n\t\tsuper(HorarioForm, self).__init__(*args,**kwargs)\n\t\tself.fields['curso_paralelo'].initial = curso_paralelo\n\t\tself.fields['periodo'].initial = periodo\n\t\tself.fields['asignatura'].queryset = models.Asignatura.objects.filter(curso = curso)\n\n\nclass HorarioEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Horario\t\n\t\tfields = [\n\t\t\t'id_horario',\n\t\t\t'curso_paralelo',\n\t\t\t'asignatura',\n\t\t\t'dia',\n\t\t\t'hora',\t\t\n\t\t\t'periodo',\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_horario': 'Horario' ,\n\t\t\t'curso_paralelo': 'Curso - Paralelo',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'dia': 'Día',\n\t\t\t'hora': 'Número de horas',\n\t\t\t'periodo': 'Periodo',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_horario': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\t'placeholder': 'Ingrese el código',\n\t\t\t\t'id' : 'id_horario',\n\t\t\t\t}),\n\t\t\t'curso_paralelo': forms.TextInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'asignatura': forms.Select(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\n\t\t\t'dia': forms.Select(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'id' : 'dia',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}), \n\t\t\t'hora': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'placeholder': 'Ingrese el número de horas',\n\t\t\t\t'id' : 'hora',\n 'onkeypress' : 'return soloNumeros(event);',\n 'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\t\t\n\t\t\t'periodo': forms.TextInput(attrs={\n\t\t\t\t'class':'form-control',\n\t\t\t\t'required' : 'true',\n\t\t\t\t}),\t\t\n\t\t}\n\n\tdef clean(self):\n\t\tperiodo = self.cleaned_data.get('periodo')\n\t\thora = self.cleaned_data.get('hora')\n\t\tdia = self.cleaned_data.get('dia')\n\t\tasignatura = self.cleaned_data.get('asignatura')\n\t\tcurso_paralelo = self.cleaned_data.get('curso_paralelo')\n\t\tcantidad_horario = len(models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora, dia = dia))\n\t\tcreditos = models.Asignatura.objects.get(id_asignatura = asignatura.id_asignatura).nro_creditos\n\n\t\tif hora <= 0:\n\t\t\traise forms.ValidationError('Indique una hora mayor a cero')\n\t\telse:\n\t\t\tif cantidad_horario == 1:\n\t\t\t\traise forms.ValidationError('Ya se ha establecido ' + str(hora) + ' hora(s) el día ' + str(dia) + ' para ' + str(asignatura))\t\n\t\t\telse:\n\t\t\t\tcantidad_horario = len(models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora)) #cambiar dia\n\t\t\t\thorario = models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora)\n\t\t\t\tif cantidad_horario >= 1:\n\t\t\t\t\thorario = models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo).exclude(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, hora = hora)\n\t\t\t\t\tif str(dia) == str(horario.dia):\n\t\t\t\t\t\traise forms.ValidationError('Ya se ha establecido el día ' + str(dia) + ' para ' + str(asignatura))\t\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn super(HorarioEditForm,self).clean()\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tcantidad_horario = len(models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, dia = dia)) #cambiar hora\n\t\t\t\t\tif cantidad_horario >= 1:\n\t\t\t\t\t\thorario = models.Horario.objects.filter(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo).exclude(periodo = periodo, asignatura = asignatura, curso_paralelo = curso_paralelo, dia = dia)\n\t\t\t\t\t\tif (hora + horario.hora) == creditos:\n\t\t\t\t\t\t\treturn super(HorarioEditForm,self).clean()\n\t\t\t\t\traise forms.ValidationError('Cambie el día o la hora, uno a la vez')\t\n\t\t\t\t\t\t\n\t\t\nclass SeguimientoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Seguimiento\t\n\t\tfields = [\n\t\t\t'id_seguimiento',\n\t\t\t'fecha',\n\t\t\t'porcentaje_real',\n\t\t\t'porcentaje_ideal',\n\t\t\t'estudiante',\n\t\t\t'observacion',\n\t\t\t'asignatura',\n\t\t\t'semana',\n\t\t\t'periodo',\t\t\n\t\t\t'estado_seguimiento',\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_seguimiento': 'Código',\n\t\t\t'fecha': 'Fecha',\n\t\t\t'porcentaje_real': 'Valor real',\n\t\t\t'porcentaje_ideal': 'Valor ideal',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'observacion': 'Observación',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'semana': 'Semana',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'estado_seguimiento': 'Estado',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_seguimiento': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t#'fecha': forms.DateInput(attrs={'class': 'vDateField'}),\n\t\t\t'fecha': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t\t'porcentaje_real': forms.TextInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'onkeypress' : 'return soloNumerosYDecimales(this, event);',\n\t\t\t\t'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\n\t\t\t'porcentaje_ideal': forms.TextInput(attrs={'class': 'form-control'}),\n\t\t\t'estudiante': forms.HiddenInput(attrs={'class':'form-control'}),\t\t\n\t\t\t'observacion': forms.Textarea(attrs={\n\t\t\t\t'rows': 2, \n\t\t\t\t'cols': 40, \n\t\t\t\t'style': 'height: auto;' 'width: calc(100% - 0px);',\n\t\t\t\t'placeholder': 'Observaciones ...'}),\n\t\t\t'asignatura': forms.Select(attrs={'class':'form-control', 'placeholder': 'Ingrese la Asignatura'}),\n\t\t\t'semana': forms.HiddenInput(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.HiddenInput(attrs={'class': 'form-control'}),\n\t\t\t'estado_seguimiento': forms.HiddenInput(attrs={'class': 'form-control'}),\t\t\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tcurso = kwargs.pop('curso')\n\t\tcarrera = kwargs.pop('carrera')\n\t\tperiodo = kwargs.pop('periodo')\n\t\talumno = kwargs.pop('alumno')\n\t\tsemana = kwargs.pop('semana')\n\n\t\tsuper(SeguimientoForm, self).__init__(*args, **kwargs)\n\t\tself.fields['asignatura'].queryset = models.Asignatura.objects.filter(curso = curso, carrera = carrera)\n\t\tself.fields['periodo'].initial = periodo\n\t\tself.fields['estudiante'].initial = alumno\n\t\tself.fields['semana'].initial = semana\n\t\tself.fields['estado_seguimiento'].initial = True\n\t\tself.fields['observacion'].required = False\n\t\tself.fields['porcentaje_real'].required = True\n\t\tself.fields['porcentaje_ideal'].required = True\n\t\tself.fields['fecha'].required = True\n\t\tself.fields['asignatura'].required = True\n\n\tdef clean(self):\n\t\tporcentaje_real = self.cleaned_data.get(\"porcentaje_real\")\n\t\tif porcentaje_real <= 0:\n\t\t\traise forms.ValidationError('No puede ingresar porcentajes menores a cero')\n\t\telse:\n\t\t\treturn super(SeguimientoForm,self).clean()\n\n\nclass SeguimientoEditForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Seguimiento\t\n\t\tfields = [\n\t\t\t'id_seguimiento',\n\t\t\t'fecha',\n\t\t\t'porcentaje_real',\n\t\t\t'porcentaje_ideal',\n\t\t\t'estudiante',\n\t\t\t'observacion',\n\t\t\t'asignatura',\n\t\t\t'semana',\n\t\t\t'periodo',\t\n\t\t\t'docente',\t\t\n\t\t\t'curso_paralelo',\t\t\t\n\t\t]\n\t\tlabels = {\n\t\t\t'id_seguimiento': 'Código',\n\t\t\t'fecha': 'Fecha',\n\t\t\t'porcentaje_real': 'Valor real',\n\t\t\t'porcentaje_ideal': 'Valor ideal',\n\t\t\t'estudiante': 'Estudiante',\n\t\t\t'observacion': 'Observación',\n\t\t\t'asignatura': 'Asignatura',\n\t\t\t'semana': 'Semana',\n\t\t\t'periodo': 'Periodo',\n\t\t\t'docente': 'Docente',\n\t\t\t'curso_paralelo': 'Curso',\n\t\t}\n\t\twidgets = {\n\t\t\t'id_seguimiento': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Ingrese el código'}),\n\t\t\t#'fecha': forms.DateInput(attrs={'class': 'vDateField'}),\n\t\t\t'fecha': forms.DateInput(format = '%Y-%m-%d',attrs={'type': 'date', 'class': 'form-control'}),\n\t\t\t'porcentaje_real': forms.TextInput(attrs={\n\t\t\t\t'class': 'form-control',\n\t\t\t\t'onkeypress' : 'return soloNumerosYDecimales(this, event);',\n\t\t\t\t'autocomplete' : 'off',\n 'required' : 'true',\n 'type':'number',\n\t\t\t\t}),\n\t\t\t'porcentaje_ideal': forms.HiddenInput(attrs={'class': 'form-control'}),\n\t\t\t'estudiante': forms.TextInput(attrs={'class':'form-control'}),\t\t\n\t\t\t'observacion': forms.Textarea(attrs={\n\t\t\t\t'rows': 2, \n\t\t\t\t'cols': 40, \n\t\t\t\t'style': 'height: auto;' 'width: calc(100% - 0px);',\n\t\t\t\t'placeholder': 'Observaciones ...'}),\n\t\t\t'asignatura': forms.Select(attrs={'class':'form-control', 'placeholder': 'Ingrese la Asignatura'}),\n\t\t\t'semana': forms.TextInput(attrs={'class':'form-control'}),\n\t\t\t'periodo': forms.TextInput(attrs={'class': 'form-control'}),\n\t\t\t'docente': forms.TextInput(attrs={'class': 'form-control'}),\t\t\n\t\t\t'curso_paralelo': forms.TextInput(attrs={'class': 'form-control'}),\n\t\t}\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(SeguimientoEditForm, self).__init__(*args, **kwargs)\n\t\tself.fields['observacion'].required = False\n\t\tself.fields['porcentaje_real'].required = True\n\t\tself.fields['fecha'].required = True\n\t\tself.fields['asignatura'].required = True\n\n\tdef clean(self):\n\t\tperiodo = self.cleaned_data.get(\"periodo\")\n\t\tfecha_inicio = periodo.fecha_inicio\n\t\tfecha_fin = periodo.fecha_fin\n\t\tfecha_seguimiento = self.cleaned_data.get(\"fecha\")\n\t\tporcentaje_real = self.cleaned_data.get(\"porcentaje_real\")\n\t\tporcentaje_ideal = self.cleaned_data.get(\"porcentaje_ideal\")\n\t\tobservacion = self.cleaned_data.get(\"observacion\")\n\t\tsemana = self.cleaned_data.get(\"semana\")\n\t\tmateria = self.cleaned_data.get(\"asignatura\")\n\t\talumno = self.cleaned_data.get(\"estudiante\")\n\t\tcurso_paralelo = self.cleaned_data.get(\"curso_paralelo\")\n\t\tseguimiento = models.Seguimiento.objects.get(periodo = periodo, asignatura = materia, curso_paralelo = curso_paralelo, estudiante=alumno, semana = semana, fecha = fecha_seguimiento)\n\t\t\n\t\tif porcentaje_real <= 0:\n\t\t\traise forms.ValidationError('No puede ingresar porcentajes menores a cero')\n\t\telse:\n\t\t\tif fecha_inicio <= fecha_seguimiento and fecha_seguimiento <= fecha_fin:\n\t\t\t\tif (float(porcentaje_real) > float(porcentaje_ideal) and observacion == ''):\n\t\t\t\t\traise forms.ValidationError('El porcentaje real supera al ideal. Especifique alguna observación' )\n\t\t\t\telif (float(porcentaje_real) < float(porcentaje_ideal) and observacion == ''):\n\t\t\t\t\traise forms.ValidationError('El porcentaje real es inferior al ideal. Especifique alguna observación' )\n\t\t\t\telse:\n\t\t\t\t\tif float(porcentaje_ideal) > 100:\n\t\t\t\t\t\traise forms.ValidationError('El porcentaje ideal semanal no puede superar el 100% ' )\n\t\t\t\t\telse:\n\t\t\t\t\t\tporcentajes_sin_incluir_valor_real_actual = models.Seguimiento.objects.filter(periodo = periodo, asignatura = materia, curso_paralelo = curso_paralelo).exclude(id_seguimiento = seguimiento.id_seguimiento)\n\t\t\t\t\t\tvalor_real_total = 0\n\t\t\t\t\t\tvalor_ideal_total = porcentaje_ideal\n\t\t\t\t\t\tfor row in porcentajes_sin_incluir_valor_real_actual: #recorrer valores por semana\n\t\t\t\t\t\t\tvalor_real_total = valor_real_total + row.porcentaje_real\n\t\t\t\t\t\t\tvalor_ideal_total = valor_ideal_total + row.porcentaje_ideal\n\n\t\t\t\t\t\tif valor_ideal_total >= (valor_real_total+porcentaje_real):\n\t\t\t\t\t\t\treturn super(SeguimientoEditForm,self).clean()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise forms.ValidationError('La sumatoria del porcentaje real no puede superar la sumatoria del porcentaje ideal ' )\t\n\t\t\telse:\n\t\t\t\traise forms.ValidationError('La fecha ingresada: ' + str(fecha_seguimiento) + ' no es válida. Dicha fecha debe estar entre el rango: ' + str(fecha_inicio) + ' - ' + str(fecha_fin) )\n","sub_path":"SISTEMA_SEGUIMIENTO_SYLLABUS/apps/administrador/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":43238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"549499603","text":"from __future__ import division\n#from builtins import str\nfrom builtins import range\nfrom past.utils import old_div\nfrom builtins import object\nimport uuid\nimport copy\nimport os\nimport time\n\nimport vodka.app\nimport vodka.data\nimport vodka.data.renderers\nimport vodka.config\nimport vodka.plugins\nimport vodka.plugins.zeromq\n\nimport graphsrv.group\n\n#FIXME: these need to be abstracted in wsgi plugin\nfrom flask import request\n\nclass GraphSourcePlugin(vodka.plugins.TimedPlugin):\n \"\"\"\n Graph data source plugin\n \"\"\"\n\n @property\n def type_name(self):\n return self.get_config(\"type\")\n\n def push(self, plots, ts=None):\n \n if not ts:\n ts = time.time()\n\n vodka.data.handle(\n self.type_name,\n {\n \"data\": plots,\n \"ts\" : ts\n },\n data_id=self.name,\n caller=self\n )\n\n\n\n\nclass Graph(object):\n \n class Configuration(vodka.config.Handler):\n\n format_y = vodka.config.Attribute(\n str,\n default=\"ms\",\n #FIXME: should be dynamic\n choices=[\"ms\"],\n help_text=\"formatter for y axis labels\"\n )\n\n precision_y = vodka.config.Attribute(\n int,\n default=2,\n help_text=\"float precision\"\n )\n\n size_y = vodka.config.Attribute(\n float,\n default=0.25,\n help_text=\"tick size on the y axis\"\n )\n\n sizes_x = vodka.config.Attribute(\n list,\n default=[3000],\n help_text=\"valid sizes for the x axis - this should be a list of intervals you want to support for viewing. (ms)\"\n )\n\n type = vodka.config.Attribute(\n str,\n #FIXME: should be dynamic\n choices=[\"multitarget\", \"smokestack\"],\n help_text=\"graph type\"\n )\n\n plot_y = vodka.config.Attribute(\n str,\n help_text=\"plot this value on the y axis (data field name)\"\n )\n\n id_field = vodka.config.Attribute(\n str,\n help_text=\"the field by which a record in the data set is uniquely identified\"\n )\n\n\n\n@vodka.app.register('graphsrv')\nclass GraphServ(vodka.app.WebApplication):\n # configuration\n\n class Configuration(vodka.app.WebApplication.Configuration):\n \n layout_config_file = vodka.config.Attribute(\n vodka.config.validators.path,\n default=lambda x,i: i.resource(\"etc/layouts.yaml\"),\n help_text=\"location of your layout configuration file\"\n )\n\n graphs = vodka.config.Attribute(\n dict,\n default={},\n help_text=\"graph configuration\",\n handler=lambda k,v: Graph\n )\n\n groups = vodka.config.Attribute(\n dict,\n default={},\n help_text=\"data groups\"\n )\n\n # application methods\n\n def setup(self):\n super(GraphServ, self).setup()\n self.layout_last_sync = 0\n graphsrv.group.add_all(self.get_config(\"groups\"))\n\n def data(self, source):\n data, _ = graphsrv.group.get_from_path(source)\n return data\n\n def data_type(self, source):\n return source\n\n def overview_read_file(self):\n return \"\"\n\n def sync_layout_config(self):\n path = self.get_config(\"layout_config_file\")\n mtime = os.path.getmtime(path)\n\n\n if not self.layout_last_sync or self.layout_last_sync != mtime:\n self.log.debug(\"%s has changed, reloading layout config...\"%path)\n self.layouts= vodka.config.Config()\n self.layouts.read(config_file=path)\n self.layout_last_sync = mtime\n\n return self.layouts\n \n\n def overview_view(self):\n \"\"\"\n Renders the overview which can hold several graphs\n and is built via config\n \"\"\"\n self.sync_layout_config()\n \n layouts = self.layouts.get(\"layouts\")\n graphs = self.config.get(\"graphs\")\n\n if \"layout\" in request.args:\n _layout = layouts.get(request.args[\"layout\"])\n else:\n _layout = list(layouts.values())[0]\n\n layout = copy.deepcopy(_layout)\n \n source = layout.get(\"source\", request.args.get(\"source\"))\n\n if source:\n title = layout.get(\"title\", source)\n else:\n title = layout.get(\"title\", \"overview\")\n\n sources = [source]\n\n ids = 1\n\n if layout.get(\"type\") == \"index\":\n # index layout, auto generate grid\n\n grid = [int(x) for x in layout.get(\"grid\", \"3x3\").split(\"x\")]\n\n sources = layout.get(\"sources\", graphsrv.group.get_paths())\n\n layout[\"layout\"] = [\n {\n \"cols\" : [\n {\n \"graph\" : copy.deepcopy(layout.get(\"graph\")),\n \"width\" : int(old_div(12,grid[0]))\n } for _ in range(0, grid[0])\n ],\n \"height\" : float(old_div(100.00,float(grid[1])))\n } for _ in range(0, grid[1])\n ]\n \n\n for row in layout.get(\"layout\"):\n for col in row.get(\"cols\",[]):\n if \"graph\" in col:\n cfg = graphs.get(col[\"graph\"].get(\"config\"))\n if \"targets\" not in cfg:\n cfg[\"targets\"] = [{\"target\":\"all\"}]\n\n col[\"graph\"][\"config_dict\"] =cfg\n if layout.get(\"type\") == \"index\":\n if sources:\n col[\"graph\"][\"source\"] = sources.pop(0)\n if not col[\"graph\"].get(\"id\"):\n col[\"graph\"][\"id\"] = \"auto-%s\" % ids\n ids +=1 \n else:\n col[\"graph\"][\"source\"] = sources[0]\n\n return self.render(\n \"overview.html\", \n self.wsgi_plugin.request_env(layout=layout, source=source, title=title)\n )\n \n def graph_view(self):\n \"\"\"\n Renders graph.js\n \"\"\"\n\n source = request.args.get(\"source\")\n \n if not source:\n raise ValueError(\"No source specified\")\n\n data_type = self.data_type(source)\n\n graphs = self.config.get(\"graphs\")\n\n source_config = graphsrv.group.get_config_from_path(source)\n\n if \"config\" in request.args:\n graph_config = graphs.get(request.args.get(\"config\"))\n else:\n graph_config = {}\n\n valid_tick_sizes = graph_config.get(\"sizes_x\", [3000])\n tick_size = int(request.args.get(\"size\", valid_tick_sizes[0]))\n\n if tick_size not in valid_tick_sizes:\n tick_size = valid_tick_sizes[0]\n \n graph_types = []\n for _, g in list(graphs.items()):\n if g.get(\"type\") not in graph_types:\n graph_types.append(g.get(\"type\"))\n\n\n variables = {\n \"type\" : request.args.get(\"type\", \"multitarget\"),\n \"source\" : source,\n \"graph_types\" : graph_types,\n \"graphConfig\" : graph_config,\n \"maxTicks\" : int(self.config.get(\"max_ticks\", 500)),\n \"dataType\" : data_type,\n \"tickSize\" : tick_size,\n \"targets\" : request.args.get(\"targets\", \"\"),\n \"fit\" : request.args.get(\"fit\", \"no\"),\n \"id\" : request.args.get(\"id\", str(uuid.uuid4()))\n } \n\n # for detail charts we only allow one target\n if variables[\"type\"] in [\"detail\"]:\n variables[\"targets\"] = variables[\"targets\"].split(\",\")[0]\n\n self.sync_layout_config()\n\n variables[\"graphConfig\"][\"targets\"] = graphsrv.group.get_config_from_path(source).get(\"targets\")\n\n return self.render(\"graph.js\", self.wsgi_plugin.request_env(**variables))\n\n def collect_targets(self, data, source):\n for row in self.data(source):\n for target in list(row[\"data\"].keys()):\n if target not in data and target[0] != \"_\":\n data.append(target)\n\n\n @vodka.data.renderers.RPC(errors=True)\n def targets(self, data, *args, **kwargs):\n \"\"\"\n Returns a json response containing all available\n targets (that have been collected from incoming\n data)\n \"\"\"\n source = request.values.get(\"source\")\n \n if not source:\n raise ValueError(\"No source specified\")\n\n self.collect_targets(data, source)\n\n\n def collect_graph_data(self, data, targets, source, ts=0.0):\n\n \"\"\"\n collect graph data from specified source\n\n data - collect into this container\n targets - list of target ids, only collect those targets\n source - storage data id\n ts - if specified only collect targets that were updated past this timestamp (seconds)\n \"\"\"\n\n \n cdata = self.data(source)\n\n for row in cdata:\n if ts and ts >= row[\"ts\"]:\n continue\n\n rdata = row[\"data\"]\n \n rv_row = {\"ts\" : row[\"ts\"], \"data\":{}}\n\n if \"all\" in targets:\n for target,bars in list(rdata.items()):\n rv_row[\"data\"][target] = bars\n else:\n for target in targets:\n if target in rdata:\n rv_row[\"data\"][target] = rdata.get(target)\n \n data.append(rv_row)\n \n\n\n @vodka.data.renderers.RPC(errors=True)\n def graph_data(self, data, *args, **kwargs):\n \"\"\"\n Returns a json response containing graph data\n \"\"\"\n\n targets = request.values.get(\"targets\",\"\").split(\",\")\n ts = float(request.values.get(\"ts\",0))\n source = request.values.get(\"source\")\n\n if not source:\n raise ValueError(\"No source specified\")\n\n if not len(targets):\n raise ValueError(\"Target targets missing\")\n\n self.collect_graph_data(data, targets, source, ts=ts)\n \n \n \n","sub_path":"graphsrv/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":10137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"343162846","text":"import pypcd\nimport os\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\nfrom sklearn import mixture\nfrom itertools import cycle\n\n\n# Input file\nsrc_file = \"~/Research/jresearch/2016-06-23-textiles-ironing/hoodie2/colored_mesh_1.ply-output.pcd\"\nsrc_file = os.path.abspath(os.path.expanduser(src_file))\n\nif __name__ == \"__main__\":\n # Load point cloud\n point_cloud = pypcd.PointCloud.from_path(src_file)\n\n # center the point cloud (xy)\n point_cloud.pc_data['x'] -= point_cloud.pc_data['x'].mean()\n point_cloud.pc_data['y'] -= point_cloud.pc_data['y'].mean()\n\n data = point_cloud.pc_data\n X = np.array([ [i, j, k] for (i, j, k) in zip(data['x'], data['y'], data['z'])])\n\n fig = plt.figure()\n #ax = fig.add_subplot(111, projection='3d')\n #ax.scatter(data[:,0], data[:,1], data[:,2], c='r', marker='o')\n plt.scatter(X[:,0], X[:,1], c='r', marker='.')\n plt.show()\n\n lowest_bic = np.infty\n bic = []\n n_components_range = range(1, 27)\n cv_types = ['spherical', 'tied', 'diag', 'full']\n for cv_type in cv_types:\n for n_components in n_components_range:\n # Fit a mixture of Gaussians with EM\n gmm = mixture.GMM(n_components=n_components, covariance_type=cv_type)\n gmm.fit(X)\n bic.append(gmm.bic(X))\n if bic[-1] < lowest_bic:\n lowest_bic = bic[-1]\n best_gmm = gmm\n\n bic = np.array(bic)\n color_iter = cycle(['k', 'r', 'g', 'b', 'c', 'm', 'y'])\n clf = best_gmm\n bars = []\n\n # Plot the BIC scores\n spl = plt.subplot(2, 1, 1)\n for i, (cv_type, color) in enumerate(zip(cv_types, color_iter)):\n xpos = np.array(n_components_range) + .2 * (i - 2)\n bars.append(plt.bar(xpos, bic[i * len(n_components_range):\n (i + 1) * len(n_components_range)],\n width=.2, color=color))\n plt.xticks(n_components_range)\n plt.ylim([bic.min() * 1.01 - .01 * bic.max(), bic.max()])\n plt.title('BIC score per model')\n xpos = np.mod(bic.argmin(), len(n_components_range)) + .65 +\\\n .2 * np.floor(bic.argmin() / len(n_components_range))\n plt.text(xpos, bic.min() * 0.97 + .03 * bic.max(), '*', fontsize=14)\n spl.set_xlabel('Number of components')\n spl.legend([b[0] for b in bars], cv_types)\n\n plt.show()","sub_path":"ironing/perception/wrinkle_detector.py","file_name":"wrinkle_detector.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"362438747","text":"# -*- encoding: utf-8 -*-\n'''\n@Filename : settings.py\n@Datetime : 2020/08/31 16:18:07\n@Author : Joe-Bu\n@version : 1.0\n'''\n\n\"\"\" 评价配置文件 \"\"\"\n\nfrom datetime import datetime\n\n\n''' Normal Prams '''\nstart = datetime(2020, 7, 10, 0, 0)\n# start = datetime(2020, 7, 31, 0, 0)\nend = datetime(2020, 8, 1, 0, 0)\n\nTZONE = 30\nINDEX = 'CODMn'\nFREQ = 4\nSCALE = 42\nEVALUATE_SCALE = 42\n\n# ------------------------\n\n''' Path Params '''\n\npaths = dict(\n in_path = r'../../output',\n out_path = r'../../output/',\n out_eval = r'../../output/evaluate/{0}/{1}/'.format(INDEX, EVALUATE_SCALE),\n model_path = r'../../model'\n)\n# filename = u'沿江渡4h验证原始数据-线性扩展.xls'\nfilename = u'洛宁长水4h验证原始数据-线性扩展.xls'\n","sub_path":"src/DataEvaluate/.ipynb_checkpoints/settings-checkpoint.py","file_name":"settings-checkpoint.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"40269899","text":"my = __import__(\"0071_custom_singly_linked_list\")\r\n\r\ndef sumList(llA, llB):\r\n n1 = llA.head\r\n n2 = llB.head\r\n carry = 0\r\n ll = my.LinkedList()\r\n while n1 or n2:\r\n result = carry\r\n if n1:\r\n result += n1.value\r\n n1 = n1.next\r\n if n2:\r\n result += n2.value\r\n n2 = n2.next\r\n ll.add(int(result % 10))\r\n carry = result / 10\r\n if int(carry) != 0:\r\n ll.add(int(carry))\r\n return ll\r\n\r\nllA = my.LinkedList()\r\nllA.add(2)\r\nllA.add(0)\r\nllA.add(5)\r\n\r\nllB = my.LinkedList()\r\nllB.add(9)\r\nllB.add(6)\r\nllB.add(5)\r\n\r\nprint(llA)\r\nprint(llB)\r\n\r\nprint(sumList(llA, llB))\r\n","sub_path":"zzz_dsa/python_dsa_2/0075_sum_of_2_nos_reversed_in_2_linked_lists.py","file_name":"0075_sum_of_2_nos_reversed_in_2_linked_lists.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"574352777","text":"import datetime\nimport pytest\nfrom dateutil.tz import tzutc\nimport accloudtant.aws.instance\nfrom conftest import MockEC2Instance\n\n\ndef test_instance():\n az = 'us-east-1b'\n region = 'us-east-1'\n instance_data = {\n 'id': 'i-1840273e',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app1',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': az,\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'RHEL Linux', },\n }\n\n\n ec2_instance = MockEC2Instance(instance_data)\n instance = accloudtant.aws.instance.Instance(ec2_instance)\n\n assert(instance.id == ec2_instance.id)\n assert(instance.reserved == 'No')\n assert(instance.name == ec2_instance.tags[0]['Value'])\n assert(instance.size == ec2_instance.instance_type)\n assert(instance.availability_zone == az)\n assert(instance.region == region)\n assert(instance.operating_system == 'Red Hat Enterprise Linux')\n assert(instance.key == 'rhel')\n assert(instance.state == ec2_instance.state['Name'])\n assert(instance.current == 0.0)\n assert(instance.best == 0.0)\n\n with pytest.raises(ValueError):\n instance.reserved = 'Maybe'\n\n instance.current = 0.392\n instance.best = 0.293\n\n assert(instance.current == 0.392)\n assert(instance.best == 0.293)\n\n\ndef test_guess_os():\n instance_data_win = {\n 'id': 'i-912a4392',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'web1',\n }, ],\n 'instance_type': 'c3.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1c',\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc(),\n ),\n 'console_output': {'Output': 'Windows', },\n }\n instance_data_rhel = {\n 'id': 'i-1840273e',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app1',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1b',\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'RHEL Linux', },\n }\n instance_data_sles = {\n 'id': 'i-9840273d',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app2',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1c',\n },\n 'state': {\n 'Name': 'stopped',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'SUSE Linux', },\n }\n instance_data_linux = {\n 'id': 'i-1840273c',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'database2',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': 'us-east-1c',\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'Linux', },\n }\n\n ec2_instance_win = MockEC2Instance(instance_data_win)\n ec2_instance_rhel = MockEC2Instance(instance_data_rhel)\n ec2_instance_sles = MockEC2Instance(instance_data_sles)\n ec2_instance_linux = MockEC2Instance(instance_data_linux)\n instance_win = accloudtant.aws.instance.Instance(ec2_instance_win)\n instance_rhel = accloudtant.aws.instance.Instance(ec2_instance_rhel)\n instance_sles = accloudtant.aws.instance.Instance(ec2_instance_sles)\n instance_linux = accloudtant.aws.instance.Instance(ec2_instance_linux)\n\n assert(instance_win.operating_system == 'Windows')\n assert(instance_rhel.operating_system == 'Red Hat Enterprise Linux')\n assert(instance_sles.operating_system == 'SUSE Linux')\n assert(instance_linux.operating_system == 'Linux/UNIX')\n\n\ndef test_match_reserved_instance():\n az = 'us-east-1b'\n instance_data = {\n 'id': 'i-1840273e',\n 'tags': [{\n 'Key': 'Name',\n 'Value': 'app1',\n }, ],\n 'instance_type': 'r2.8xlarge',\n 'placement': {\n 'AvailabilityZone': az,\n },\n 'state': {\n 'Name': 'running',\n },\n 'launch_time': datetime.datetime(\n 2015,\n 10,\n 22,\n 14,\n 15,\n 10,\n tzinfo=tzutc()\n ),\n 'console_output': {'Output': 'RHEL Linux', },\n }\n reserved_instance = {\n 'ProductDescription': 'Red Hat Enterprise Linux',\n 'InstanceTenancy': 'default',\n 'InstanceCount': 1,\n 'InstanceType': 'r2.8xlarge',\n 'Start': datetime.datetime(\n 2011,\n 6,\n 5,\n 6,\n 20,\n 10,\n 494000,\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n 'End': datetime.datetime(\n 2011,\n 6,\n 5,\n 6,\n 20,\n 10,\n tzinfo=tzutc()\n ),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233321',\n 'FixedPrice': 910.0,\n 'AvailabilityZone': 'us-east-1b',\n 'UsagePrice': 0.12,\n 'Duration': 31536000,\n 'State': 'active',\n }\n\n ec2_instance = MockEC2Instance(instance_data)\n instance = accloudtant.aws.instance.Instance(ec2_instance)\n reserved_instance['InstancesLeft'] = reserved_instance['InstanceCount']\n\n assert(instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['State'] = 'pending'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['State'] = 'active'\n reserved_instance['InstancesLeft'] = 0\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['InstacesLeft'] = 1\n reserved_instance['ProductDescription'] = 'Windows'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['ProductionDescription'] = 'Red Hat Enterprise Linux'\n reserved_instance['InstaceType'] = 't1.micro'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n\n reserved_instance['InstaceType'] = 'r2.8xlarge'\n reserved_instance['AvailabilityZone'] = 'us-east-1c'\n\n assert(not instance.match_reserved_instance(reserved_instance))\n","sub_path":"tests/aws/test_instance.py","file_name":"test_instance.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"225855224","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 7 14:53:43 2019\r\n\r\n@author: vr_lab\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pdb\r\nimport random\r\nimport vtk\r\n\r\ndef select_points(filename):\r\n reader = vtk.vtkSTLReader()\r\n reader.SetFileName(filename)\r\n reader.Update()\r\n data = reader.GetOutput() \r\n n_points = data.GetNumberOfPoints()\r\n mesh_points = np.zeros([n_points, 3])\r\n for i in range(n_points):\r\n mesh_points[i][0], mesh_points[i][1], mesh_points[i][\t2] = data.GetPoint(i)\r\n point_indices = []\r\n for i in range(0,20):\r\n point_index = random.randint(1, n_points)\r\n point_indices.append(mesh_points[point_index, :]) \r\n return point_indices\r\n\r\ndef write_to_file(filename, points):\r\n output_file = open(filename, 'w')\r\n for index, point in enumerate(points):\r\n output_file.write(str(index) + ' ' + str(point[0]) + ' ' + str(point[1]) + \r\n ' ' + str(point[2]) + '\\n')\r\n output_file.close()\r\n \r\nif __name__ == '__main__':\r\n input_file = 'FGlandular.stl'\r\n output_file = \"Fat_Solid_32837pointspoints.a.node\"\r\n points = select_points(input_file)\r\n write_to_file(output_file, points)","sub_path":"ChangeAbaqusInput/random_select_point_from_organ.py","file_name":"random_select_point_from_organ.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"262431134","text":"from itertools import starmap\nfrom typing import Dict, List, Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch_scatter as scatter\n\nfrom transformers.configuration_bert import BertConfig\nfrom transformers.modeling_bert import BertForSequenceClassification as OrigBertForSequenceClassification\nfrom transformers.modeling_bert import BertModel, BertPreTrainedModel\n\n\nclass SimpleConcatAvgMaxTokensPooler(nn.Module):\n def __init__(self, config):\n super(SimpleConcatAvgMaxTokensPooler, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool1d(1)\n self.max_pool = nn.AdaptiveMaxPool1d(1)\n\n def forward(self, tokens_embs: torch.Tensor, *args) -> torch.Tensor: # type: ignore\n return torch.cat([self.avg_pool(tokens_embs).squeeze(), self.max_pool(tokens_embs).squeeze()], dim=0).squeeze()\n\n\nclass SimpleAvgOrMaxTokensPoolerWithMask(nn.Module):\n def __init__(self, config):\n super(SimpleAvgOrMaxTokensPoolerWithMask, self).__init__()\n word_tokens_pooling_method = getattr(config, \"word_tokens_pooling_method\", \"\").lower().capitalize()\n self.pooler = getattr(nn, f\"Adaptive{word_tokens_pooling_method}Pool1d\")(1)\n\n def forward(self, tensor: torch.Tensor) -> torch.Tensor:\n return self.pooler(tensor).squeeze()\n\n\nclass CustomBertForNer(BertPreTrainedModel):\n def __init__(self, config):\n super(CustomBertForNer, self).__init__(config)\n word_tokens_pooling_method = getattr(config, \"word_tokens_pooling_method\", \"\").lower()\n linear_hidden_size_mult = 1\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n if word_tokens_pooling_method in [\"avg\", \"max\"]:\n self.tokens_pooler = SimpleAvgOrMaxTokensPoolerWithMask(config)\n elif word_tokens_pooling_method == \"concatavgmax\":\n self.tokens_pooler = SimpleConcatAvgMaxTokensPooler(config)\n linear_hidden_size_mult = 2\n\n self.classifier = nn.Linear(config.hidden_size * linear_hidden_size_mult, config.num_labels)\n\n self.init_weights()\n\n def _convert_bert_outputs_to_map(self, outputs: Tuple[torch.Tensor, ...]) -> Dict[str, torch.Tensor]:\n outputs_map = dict(last_hidden_state=outputs[0], pooler_output=outputs[1])\n\n if len(outputs) > 2:\n outputs_map[\"hidden_states\"] = outputs[2]\n if len(outputs) > 3:\n outputs_map[\"attentions\"] = outputs[3]\n\n return outputs_map\n\n def forward(\n self,\n input_ids,\n word_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n labels=None,\n ):\n outputs = self.bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n )\n outputs = self._convert_bert_outputs_to_map(outputs)\n sequence_output = outputs[\"last_hidden_state\"]\n\n if word_ids is not None and hasattr(self, \"tokens_pooler\"):\n\n word_ids[word_ids == -100] = -1\n\n _word_ids = word_ids.unsqueeze(-1) + 1\n _mean = scatter.scatter_mean(sequence_output, _word_ids, dim=1).type(sequence_output.dtype)\n _mean[:, 0, :] = sequence_output[:, 0, :]\n _max = scatter.scatter_max(sequence_output, _word_ids, dim=1, fill_value=0)[0].type(sequence_output.dtype)\n _max[:, 0, :] = sequence_output[:, 0, :]\n sequence_output = torch.cat([_mean, _max], dim=-1)\n\n word_ids[word_ids == -1] = -100\n\n if labels is not None:\n\n def transform_ids(word_ids: torch.Tensor, labels: torch.Tensor, pad_id: int = -100) -> torch.Tensor:\n word_labels = labels[\n word_ids[word_ids != pad_id].unique_consecutive(return_counts=True)[1].cumsum(dim=0) - 1\n ]\n tensor = F.pad(\n word_labels, (0, sequence_output.shape[1] - 1 - word_labels.shape[0]), value=pad_id,\n )\n return tensor\n\n labels = torch.stack(list(starmap(transform_ids, zip(word_ids[:, 1:], labels[:, 1:]))), dim=0)\n labels = torch.cat((torch.tensor(-100).repeat(labels.shape[0], 1).to(labels.device), labels), dim=1)\n attention_mask = torch.zeros_like(labels)\n attention_mask[labels != -100] = 1\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n if labels is not None:\n loss_fct = nn.CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1).type(torch.bool)\n active_logits = logits.view(-1, self.config.num_labels)[active_loss]\n active_labels = labels.view(-1)[active_loss]\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n outputs[\"loss\"] = loss\n\n outputs[\"attention_mask\"] = attention_mask\n outputs[\"logits\"] = logits\n\n if labels is not None:\n outputs[\"labels\"] = labels\n\n return outputs # (loss), scores, (hidden_states), (attentions)\n\n\nclass CustomBertForQuestionAnswering(BertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n def forward(\n self,\n input_ids,\n attention_mask=None,\n num_question_tokens=None,\n position_ids=None,\n head_mask=None,\n start_positions=None,\n end_positions=None,\n ):\n batch_size, seq_len = input_ids.shape\n windowed_mode = False\n\n if seq_len > self.config.max_position_embeddings:\n assert batch_size == 1, \"sliding window mode is not currently supported for batch_size > 1\"\n assert position_ids is None\n assert isinstance(num_question_tokens, int)\n\n windowed_mode = True\n\n input_ids = torch.squeeze(input_ids, dim=0)\n question_ids, paragraph_ids = torch.split(input_ids, [num_question_tokens, seq_len - num_question_tokens])\n windowed_paragraph_ids, paragraph_position_ids = self._apply_sliding_window_to_single_batch(\n paragraph_ids, self.config.max_position_embeddings - num_question_tokens\n )\n\n batch_size = windowed_paragraph_ids.shape[0]\n seq_len = self.config.max_position_embeddings\n\n input_ids = torch.cat(\n (question_ids.unsqueeze(0).expand(batch_size, num_question_tokens), windowed_paragraph_ids,), dim=-1,\n )\n\n if num_question_tokens is None:\n num_question_tokens = seq_len\n\n if isinstance(num_question_tokens, int):\n token_type_ids = (\n self._create_type_tokens_for_single_batch(num_question_tokens, seq_len)\n .unsqueeze(0)\n .expand(batch_size, seq_len)\n )\n else:\n token_type_ids = torch.stack(\n [\n self._create_type_tokens_for_single_batch(num_in_batch, seq_len)\n for num_in_batch in num_question_tokens\n ]\n )\n\n token_type_ids = token_type_ids.to(input_ids.device)\n\n outputs = self.bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n )\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n if windowed_mode:\n question_logits, paragraph_logits = torch.split(\n logits, [num_question_tokens, seq_len - num_question_tokens], dim=1\n )\n\n question_logits = question_logits.min(dim=0, keepdim=True)[0]\n paragraph_logits = self._compress_sliding_window(paragraph_logits, paragraph_position_ids)\n\n logits = torch.cat((question_logits, paragraph_logits), dim=1)\n\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n outputs = (start_logits, end_logits) + outputs[2:]\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), start_logits, end_logits, (hidden_states), (attentions)\n\n def _create_type_tokens_for_single_batch(self, num_question_tokens, seq_len):\n return torch.cat([torch.zeros(num_question_tokens), torch.ones(seq_len - num_question_tokens)]).long()\n\n def _apply_sliding_window_to_single_batch(self, tokens, window_size=512, window_stride=None):\n if window_stride is None:\n window_stride = window_size // 2\n\n result_batch = []\n result_positions = []\n\n start = end = 0\n while end < len(tokens):\n end = min(start + window_size, len(tokens))\n start = end - window_size # this allows to avoid shorter last window\n\n result_batch.append(tokens[start:end])\n result_positions.append(torch.arange(start, end))\n\n start += window_stride\n\n return torch.stack(result_batch), torch.stack(result_positions)\n\n def _compress_sliding_window(self, windowed_tokens, positions):\n num_tokens = positions.max() + 1\n window_size = windowed_tokens.shape[1]\n\n middle_positions = positions[:, window_size // 2]\n tokens_best_window_idxs = (\n (torch.unsqueeze(middle_positions, 0) - torch.arange(num_tokens).unsqueeze(-1)).abs().argmin(dim=1)\n )\n token_mask = torch.stack(\n [\n tokens_best_window_idxs[token_idxs_in_window] == window_idx\n for window_idx, token_idxs_in_window in enumerate(positions)\n ]\n )\n\n return windowed_tokens[token_mask].unsqueeze(0)\n\n\nclass BertForSequenceClassification(OrigBertForSequenceClassification):\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n pooler_name = kwargs.get(\"pooler\", None)\n if pooler_name and pooler_name.lower().startswith(\"concat\"):\n model.classifier = nn.Linear(model.config.hidden_size * 2, model.config.num_labels)\n return model\n","sub_path":"src/transformers/customs/modeling_bert.py","file_name":"modeling_bert.py","file_ext":"py","file_size_in_byte":11620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"255779250","text":"import cv2 as cv\r\nimport numpy as np\r\nimport tensorflow.contrib.slim as slim\r\nimport os\r\nimport tensorflow as tf\r\nimport random\r\nimport glob\r\nfrom tensorflow.python.framework import graph_util\r\nfrom tensorflow.python.platform import gfile \r\nimport shutil\r\n\r\ndata_test_dir = 'ucf_101_img_mul12_NECK'\r\ndata_train_dirs = ['ucf_101_img_centre_NECK','ucf_101_img_mul12_NECK','ucf_101_img_centre_top8_F_NECK']\r\nCLASS_NUM = 101\r\nBATCH_SIZE = 50\r\nlearning_rate = 0.0001\r\nITEMS = 3000\r\ndrop_rate = 0.9\r\nSPLIT_PATH = 'ucfTrainTestlist/testlist02.txt'\r\nLABEL_PATH = 'ucfTrainTestlist/classInd.txt'\r\nMODEL_DIR = 'models/'\r\nMODEL_FILE = 'SA_v1_0.759.pb'\r\nGPU = '0'\r\nTOP_DIR = 'ucf_101_img_mul12_top8'\r\nMID_DIR = 'ucf_101_img_mul12_mid35'\r\nNECK_DIR = 'ucf_101_img_mul12_NECK'\r\nOUT_DIR = 'ucf_101_img_mul12_NECK_OUT'\r\n# pb_file_path = 'full_ucfs1.pb'\r\ntest_dir = {'neck':NECK_DIR, 'top':TOP_DIR, 'pre_out':OUT_DIR, 'mid':MID_DIR}\r\ntarget_dir = {'neck':NECK_DIR+'_max2', 'top':TOP_DIR+'_max2', 'pre_out':OUT_DIR+'_max2', 'mid':MID_DIR+'_max2'}\r\n# 'neck', 'pre_out', 'top', 'if_train'\r\nshape = {'neck':(2048),'top':(8,8,1280),'mid':(35,35,288),'pre_out':(101)}\r\nmax_file = 'UCF_101_s2_SA_max.txt'\r\n\r\n\r\nclass convert_max():\r\n def __init__(self, test_dir, target_dir, max_file):\r\n self.sourse_dir = test_dir\r\n self.target_dir = target_dir\r\n self.max_file = max_file\r\n self.read_max_list()\r\n print(\"has read\")\r\n for kk in test_dir.keys():\r\n self.copy2target(self.sourse_dir[kk], self.target_dir[kk])\r\n def initial(self,dic):\r\n keys = dic.keys()\r\n for key in keys:\r\n dic[key] = []\r\n def copy2target(self, sourse_dir, target_dir):\r\n for path, index, class_name in self.max_info:\r\n glob_path = os.path.join(sourse_dir,class_name,path)+\"*\"\r\n glob_list = sorted(glob.glob(glob_path))\r\n target_path = os.path.join(target_dir,class_name,path)+'.txt'\r\n if not os.path.exists(os.path.dirname(target_path)):\r\n os.makedirs(os.path.dirname(target_path))\r\n print(os.path.dirname(target_path))\r\n shutil.copyfile(glob_list[index], target_path)\r\n def read_max_list(self):\r\n self.max_info = []\r\n with open(self.max_file) as f:\r\n line = f.readline()\r\n while len(line) > 0:\r\n lines = line.split(',')\r\n index = int(lines[1])\r\n path = os.path.basename(lines[0])\r\n class_name = os.path.basename(os.path.dirname(lines[0]))\r\n self.max_info.append((path, index, class_name))\r\n line = f.readline()\r\n\r\nconvert_max(test_dir, target_dir, max_file)\r\n\r\n\r\n # acc_list = []\r\n # index_list = []\r\n\r\n # input_tensor = tf.placeholder(dtype=tf.float32, shape=[None,192], name='input_tensor')\r\n # label_index = tf.placeholder(dtype=tf.int64, shape=[None], name='label_index')\r\n # label = tf.one_hot(label_index, CLASS_NUM)\r\n # logits = graph_def(input_tensor)\r\n # cross_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=label,logits=logits))\r\n # slim.losses.add_loss(cross_loss)\r\n # total_loss = slim.losses.get_total_loss()\r\n # train_op = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)\r\n # pre_out = tf.nn.softmax(logits, name='output')\r\n # predict_label = tf.argmax(logits,1)\r\n # correct_prediction = tf.equal(tf.argmax(label,1), tf.argmax(logits,1))\r\n # accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\n # with tf.Session(config=cuda_set(gpu='1')) as sess:\r\n # sess.run( tf.global_variables_initializer())\r\n # print(data_test_dir)\r\n # for i in range(ITEMS):\r\n # train_batch, label_batch = get_train_batch(train_path_list, train_label_list, test_set)\r\n # if (i+1)%100 == 0 :\r\n # _, loss, acc = sess.run([train_op, total_loss, accuracy],\r\n # feed_dict={input_tensor:train_batch, label_index:label_batch})\r\n # test_acc, test_loss = sess.run([accuracy, total_loss], feed_dict={input_tensor:test_batch, label_index:test_label_batch})\r\n # print(test_acc)\r\n # print(\"step %6d loss=%f acc=%f TEST_acc : %f Test_loss=%f\"%(i+1, loss, acc, test_acc, test_loss))\r\n # with open('ucf-101-img-combine-record.txt','a') as f:\r\n # acc_str = 'Step %05d TEST_acc : %f '%(i, test_acc)+'\\n'\r\n # f.write(acc_str)\r\n # else:\r\n # sess.run([train_op], feed_dict={input_tensor:train_batch, label_index:label_batch})\r\n # # _, test_acc[0] = sess.run([train_op, accuracy], feed_dict={input_tensor:test_batch, label_index:test_label_batch})\r\n # # print('TEST_acc : %f '%(test_acc[0]) )\r\n # # with open('ucf-101-img-combine-record.txt','a') as f:\r\n # # acc_str = 'TEST_acc : %f '%(test_acc[0])\r\n # # f.write(acc_str)\r\n # constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, [\"output\"])\r\n # with tf.gfile.FastGFile(pb_file_path, mode='wb') as f:\r\n # f.write(constant_graph.SerializeToString())\r\n\r\n\r\n# if __name__ == '__main__' :\r\n# # get_center_frame(data_path)\r\n# main()\r\n","sub_path":"SA_101_save_max_mid.py","file_name":"SA_101_save_max_mid.py","file_ext":"py","file_size_in_byte":5302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"402532229","text":"from tkinter import *\nimport tkinter as tk\nimport PIL\nfrom PIL import ImageTk, Image\nimport glob\nimport os\n\n# --- functions ---\n\ni = 0\nimg=0\nimagelist=[]\nimagelistname=[]\npath = 'injest/*'\nequipnumberentry = \"\"\nimagelableentry = \"\" \nimageorderentry = \"\"\nyup=\"\"\n\n\ndef text_mod():\n global i, btn2, imagelist, image, imagelistname, yup # btn can be omitted but not sure if should be\n btn2['text'] = imagelistname[i] # the global object that is modified\n yup = imagelistname[i]\n photo = load_images()\n i = (i + 1) % len(imagelistname) # another global object that gets modified\n item4 = canvas.create_image(209, 164, image=photo)\n root.mainloop()\n\ndef load_images():\n global i, btn2, imagelist, image,imagelistname, yup\n image = Image.open(yup)\n basewidth = 900\n #wpercent = (basewidth / float(image.size[0]))\n #hsize = int((float(image.size[1]) * float(wpercent)))\n image = image.resize((418,328), PIL.Image.ANTIALIAS)\n photo = ImageTk.PhotoImage(image)\n image.close()\n return photo\n\ndef resize_Image(simage):\n im = Image.open(simage)\n if im.width != 318 and im.height != 228:\n resized_im = im.resize((318,228))\n resized_im.save(simage)\n im.close()\n\ndef injest_image():\n global imagelableentry, imageorderentry, imagelistname, equipnumberentry, yup\n im = Image.open(yup)\n if im.width != 318 and im.height != 228:\n im = im.resize((318,228))\n s1=str(equipnumberentry.get())\n s2=str(imagelableentry.get())\n s3=str(imageorderentry.get())\n if not os.path.exists(\"images/\"+s1):\n os.makedirs(\"images/\"+s1)\n\n im.save(\"images/\"+s1+\"/\"+s2+\" \"+str(s3)+\".jpg\")\n im.close()\n os.remove(yup)\n imagelistname.remove(yup)\ndef image_reload():\n global imagelist, imagelistname\n imagelistname=[]\n imagelist=[]\n for filename in glob.glob(path+'/*.jpg'): #assuming gif\n im=Image.open(filename)\n imagelist.append(im)\n imagelistname.append(filename)\n im.close()\nroot=Tk()\n\n\nfor filename in glob.glob(path+'/*.jpg'): #assuming gif\n im=Image.open(filename)\n imagelist.append(im)\n imagelistname.append(filename)\n im.close()\n\ncanvas=Canvas(root, height=330, width=1000)\n\neqnlable = tk.Label(root, text='Equipment Number:')\neqnlable.config(font=('helvetica', 10))\ncanvas.create_window(550, 140, window=eqnlable)\nequipnumberentry = tk.Entry (root) \ncanvas.create_window(680, 140, window=equipnumberentry)\n\nimglable = tk.Label(root, text='Image lable:')\nimglable.config(font=('helvetica', 10))\ncanvas.create_window(550, 160, window=imglable)\nimagelableentry = tk.Entry (root) \ncanvas.create_window(680, 160, window=imagelableentry)\n\nimgorder = tk.Label(root, text='Image order ( 1-6 ):')\nimgorder.config(font=('helvetica', 10))\ncanvas.create_window(550, 180, window=imgorder)\nimageorderentry = tk.Entry (root) \ncanvas.create_window(680, 180, window=imageorderentry)\n\nbtn = tk.Button(root, text=\"Reload Image List\", height=2)\nbtn['command'] = image_reload\n\nbtn = tk.Button(root, text=\"Injest Image\", height=2, width = 20)\nbtn['command'] = injest_image\n\nbtn2 = tk.Button(root, text=\"Cycle Images\",height=2)\nbtn2['command'] = text_mod\n\nbtn.pack(fill='both', expand=True)\nbtn.place(x=600, y=300)\nbtn2.pack(fill='both', expand=True)\ncanvas.pack(side = TOP, expand=True, fill=BOTH)\nroot.mainloop()\n","sub_path":"ImageInjest.py","file_name":"ImageInjest.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"69484259","text":"\nfrom dNode import Node\n\nclass Dlist:\n def __init__(self):\n self.head= None\n\n def is_empty(self):\n return self.head ==None #if none, empty is true\n\n def add(self,item): #add at the start of list\n if self.head == None: #if the list is empty\n self.head = Node(item) #set the head's inference to the new item\n else:\n temp = Node(item)\n temp.set_next(self.head) #set the next of the item to the head\n self.head.set_previous(temp) #set the head's inference previous to temp\n self.head = temp #make the temp head\n\n def append(self,item): #add item at last\n if self.head == None: #when the list is empty, append at head\n self.head = Node(item)\n else: #when not empty list\n current = self.head\n while current.get_next() != None: #while loop until current's next is none: when node is the last node\n current = current.get_next()\n #outside while loop; current's next item is none\n temp = Node(item)\n current.set_next(temp)\n temp.set_previous(current)\n\n def insert_after(self, item, x): #insert new item after x\n if self.head == None: #when empty list there is no x\n print('List is empty!')\n\n else:\n current = self.head\n found = False\n while current != None and not found:\n if current.get_item() == x: #when we found the item we want to insert after\n found = True\n else:\n current = current.get_next()\n\n if found == False: #when x is not found : not in the list\n print('Item is not in the list')\n else:\n #change the inference of temp\n temp = Node(item)\n temp.set_next(current.get_next())\n temp.set_previous(current)\n\n if current.get_next() != None: #current is not the last item of the list\n current.get_next().set_previous(temp)\n #when current is the last item, no need to set the previous to temp since it is none\n\n current.set_next(temp) #set the current's next to temp\n\n\n def insert_before(self,item,x):\n if self.head == None:\n print('List is empty')\n else:\n current= self.head\n found = False\n while current != None and not found : #while until the current object is none(last item) or found\n if current.get_item() == x:\n found = True\n else:\n current = current.get_next()\n\n if found == False:\n print('Item is not in the list')\n\n else: #when the item is in the list\n temp = Node(item)\n temp.set_next(current)\n temp.set_previous(current.get_previous())\n #set the temp's previous and next according to the current item\n\n if current.get_previous() != None: #when the current item is not the first item in list\n current.get_previous().set_next(temp)\n\n else: #when the previous item is None (current is the first item of the list)\n self.head = temp\n current.set_previous(temp)\n def pop_first(self):\n if self.head == None:\n print('List is empty.')\n else:\n if self.head.get_next() ==None: #when there is only one item\n self.head =None #set head to None\n else:\n self.head= self.head.get_next() #make the next item of the head to the head\n self.head.set_previous(None) #make the new head's previous to None ; making it the head\n\n\n def pop_last(self):\n if self.head == None:\n print('List is empty.')\n else:\n if self.head.get_next() == None: #when the list has only one item\n self.head = None #delete that only one item\n else:\n current = self.head\n while current.get_next() != None: #until current's next item is none(last item's get next is none)\n current = current.get_next()\n\n current.get_previous().set_next(None) #set the current's previous to None\n\n def delete(self, item):\n if self.head.get_item() == item: #when the first item is the item we are looking for\n self.head = self.head.get_next()\n self.head.set_previous(None) #make the next item of head to the head and delete the previous inference\n else:\n current =self.head\n found = False\n while not found: #always found is the prerequisite\n if current.get_item() == item:\n found = True\n else:\n current = current.get_next()\n if current.get_next() != None: #when not last item\n current.get_previous().set_next(current.get_next())\n current.get_next().set_previous(current.get_previous())\n else: #when last item\n current.get_previous().set_next(None)\n\n def search(self,item):\n current = self.head\n found = False\n while current != None and not found:\n if current.get_item() == item:\n found = True\n else:\n current = current.get_next()\n return found\n\n def size(self):\n current = self.head\n count = 0\n while current != None: #while not last item\n count += 1\n current = current.get_next()\n return count\n\n\n\n\nd = Dlist()\nprint('is the list empty..? '+str(d.is_empty()))\nd.add(30)\nd.add(20)\nd.add(50)\nd.add(12)\nd.append(22)\nd.append(90)\nprint('the size of the list d is..'+ str(d.size()))\nd.pop_last()\nd.pop_first()\nd.delete(20)\nprint('the size of the list d is..'+ str(d.size()))\nprint('Is the value 22 in the list..? ' +str(d.search(22)))\nd.insert_after(99,30)\nprint('the size of the list d is..'+ str(d.size()))\nd.insert_before(100,30)\nprint('the size of the list d is..'+ str(d.size()))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2020-Data-Structure-Algorithms/dlist.py","file_name":"dlist.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"323952299","text":"from .Tex import Tex\nfrom .constants import QUOTE_FONT_SIZE\n\nclass Quote(Tex):\n \"\"\"\n class that represents a quote\n \"\"\"\n def __init__(self, quote, author='', font_size=QUOTE_FONT_SIZE):\n self.quote = quote\n self.author = author\n self.format = self._format()\n super().__init__(self.format)\n\n def _format(self):\n quote_size = QUOTE_FONT_SIZE\n quote_spacing = QUOTE_FONT_SIZE * 1.2\n\n res = ''\n res += r'\\noindent\\fontsize'\n res += f'{{{quote_size}}}{{{round(quote_spacing)}}}'\n res += rf'\\selectfont \"{self.quote}\"\\\\'\n res += rf'\\rightline{{-{self.author}}}'\n return res\n","sub_path":"objects/typesetting/Quote.py","file_name":"Quote.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"551790411","text":"# 4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...Количество элементов (n) вводится с\n# клавиатуры.\n\nSUMS = 0\n\n\n# ---Цикл---\ndef sum_nums(n):\n sums = 0\n num = 1\n for i in range(n):\n sums += num\n num = -(num/2)\n print(f'Сумма {n} элементов ряда: \"1 -0.5 0.25 -0.125 ...\" равна: {sums}')\n\n\n# ---Рекурсия---\ndef sum_nums_2(n, num): # num - элемент последовательности\n global SUMS\n if n == 0:\n return print(f'Сумма элементов ряда: \"1 -0.5 0.25 -0.125 ...\" равна: {SUMS}')\n SUMS += num\n return sum_nums_2(n-1, -(num/2))\n\n\nif __name__ == '__main__':\n N = int(input('Введите кол-во элементов ряда:\\n'))\n sum_nums(N)\n sum_nums_2(N, 1)\n","sub_path":"lesson_2/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"562239536","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom data_utils import (\n load_dialog_task, vectorize_data, load_candidates, vectorize_candidates, tokenize,\n generate_profile_encoding, IdenticalWordIdx\n)\nfrom sklearn import metrics\nfrom memn2n import MemN2NDialog\nfrom itertools import chain\nfrom six.moves import range, reduce\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport pickle\nimport pprint\nimport glob\n\ntf.flags.DEFINE_float(\"learning_rate\", 0.001, \"Learning rate for Adam Optimizer.\")\ntf.flags.DEFINE_float(\"epsilon\", 1e-8, \"Epsilon value for Adam Optimizer.\")\ntf.flags.DEFINE_float(\"max_grad_norm\", 40.0, \"Clip gradients to this norm.\")\ntf.flags.DEFINE_integer(\"evaluation_interval\", 10, \"Evaluate and print results every x epochs\")\ntf.flags.DEFINE_integer(\"batch_size\", 32, \"Batch size for training.\")\ntf.flags.DEFINE_integer(\"hops\", 3, \"Number of hops in the Memory Network.\")\ntf.flags.DEFINE_integer(\"epochs\", 200, \"Number of epochs to train for.\")\ntf.flags.DEFINE_integer(\"embedding_size\", 20, \"Embedding size for embedding matrices.\")\ntf.flags.DEFINE_integer(\"memory_size\", 250, \"Maximum size of memory.\")\ntf.flags.DEFINE_integer(\"task_id\", 1, \"task id, 1 <= id <= 5\")\ntf.flags.DEFINE_integer(\"random_state\", None, \"Random state.\")\ntf.flags.DEFINE_string(\"data_dir\", \"../data/personalized-dialog-dataset/full\", \"Directory containing bAbI tasks\")\ntf.flags.DEFINE_string(\"model_dir\", \"model/\", \"Directory containing memn2n model checkpoints\")\ntf.flags.DEFINE_boolean('train', True, 'if True, begin to train')\ntf.flags.DEFINE_boolean('interactive', False, 'if True, interactive')\ntf.flags.DEFINE_boolean('OOV', False, 'if True, use OOV test set')\ntf.flags.DEFINE_boolean('save_vocab', False, 'if True, saves vocabulary')\ntf.flags.DEFINE_boolean('load_vocab', False, 'if True, loads vocabulary instead of building it')\ntf.flags.DEFINE_boolean('verbose', False, \"if True, print different debugging messages\")\ntf.flags.DEFINE_float('alpha', .5, \"Value of the alpha parameter, used to prefer one part of the model\")\ntf.flags.DEFINE_string('experiment', None, \"Choose if any experiment to do\")\nFLAGS = tf.flags.FLAGS\nprint(\"Started Task:\", FLAGS.task_id)\n\n\nclass ChatBot(object):\n \"\"\"\n Handle a chatbot session in sense of data, training and testing. Can be seen as a\n helper class for the main function.\n \"\"\"\n def __init__(self,\n data_dir,\n model_dir,\n task_id,\n isInteractive=True,\n OOV=False,\n memory_size=250,\n random_state=None,\n batch_size=32,\n learning_rate=0.001,\n epsilon=1e-8,\n max_grad_norm=40.0,\n evaluation_interval=10,\n hops=3,\n epochs=200,\n embedding_size=20,\n alpha=.5,\n save_vocab=None,\n load_vocab=None,\n verbose=False,\n load_profiles=None,\n save_profiles=None):\n\n self.data_dir=data_dir\n self.task_id=task_id\n self.model_dir=model_dir\n # self.isTrain=isTrain\n self.isInteractive=isInteractive\n self.OOV=OOV\n self.memory_size=memory_size\n self.random_state=random_state\n self.batch_size=batch_size\n self.learning_rate=learning_rate\n self.epsilon=epsilon\n self.max_grad_norm=max_grad_norm\n self.evaluation_interval=evaluation_interval\n self.hops=hops\n self.epochs=epochs\n self.embedding_size=embedding_size\n self.save_vocab=save_vocab\n self.load_vocab=load_vocab\n self.verbose = verbose\n self.alpha = alpha\n\n # Loading possible answers\n self.candidates, self.candid2indx = load_candidates(self.data_dir, self.task_id)\n self.n_cand = len(self.candidates)\n print(\"Candidate Size\", self.n_cand)\n self.indx2candid= dict((self.candid2indx[key],key) for key in self.candid2indx)\n\n # task data\n self.trainData, self.testData, self.valData = load_dialog_task(self.data_dir, self.task_id, self.candid2indx, self.OOV)\n data = self.trainData + self.testData + self.valData\n\n # Find profiles types\n if load_profiles:\n with open(load_profiles, 'rb') as f:\n self._profiles_mapping = pickle.load(f)\n else:\n self._profiles_mapping = generate_profile_encoding(self.trainData)\n if save_profiles:\n with open(save_profiles, 'wb') as f:\n pickle.dump(self._profiles_mapping, f)\n\n profiles_idx_set = set(self._profiles_mapping.values())\n\n print(\"Profiles:\", self._profiles_mapping)\n\n # Vocabulary\n self.build_vocab(data,self.candidates,self.save_vocab,self.load_vocab)\n # self.candidates_vec=vectorize_candidates_sparse(self.candidates,self.word_idx)\n self.candidates_vec=vectorize_candidates(self.candidates,self.word_idx,self.candidate_sentence_size)\n\n # Model initialisation\n optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate, epsilon=self.epsilon)\n self.sess=tf.Session()\n self.model = MemN2NDialog(self.batch_size,\n self.vocab_size,\n self.n_cand,\n self.sentence_size,\n self.embedding_size,\n self.candidates_vec,\n profiles_idx_set,\n session=self.sess,\n hops=self.hops,\n max_grad_norm=self.max_grad_norm,\n alpha=alpha,\n optimizer=optimizer,\n task_id=task_id,\n verbose=verbose)\n self.saver = tf.train.Saver(max_to_keep=50)\n \n # self.summary_writer = tf.train.SummaryWriter(self.model.root_dir, self.model.graph_output.graph)\n self.summary_writer = tf.summary.FileWriter(self.model.root_dir, self.model.graph_output.graph)\n \n def build_vocab(self,data,candidates,save=False,load_file=None):\n \"\"\"\n Construction of a vocabulary based on all possible words in `data`. A side-effect only method.\n :param data: Typically, the concatenation of the training, testing, and validation dataset\n :param candidates: Possible bot's answers\n :param save: Name of the file to construct (or anything evaluated to `False` would not trigger the saving)\n :param load_file: Name of the file to load (or `False` if force the construction of the vocabulary\n \"\"\"\n if load_file:\n with open(load_file, 'rb') as vocab_file:\n vocab = pickle.load(vocab_file)\n else:\n vocab = reduce(lambda x, y: x | y, (set(list(chain.from_iterable(s)) + q) for s, q, a in data))\n vocab |= reduce(lambda x,y: x|y, (set(candidate) for candidate in candidates) )\n vocab=sorted(vocab)\n\n self.vocabulary = vocab\n self.word_idx = dict((c, i + 1) for i, c in enumerate(vocab))\n max_story_size = max(map(len, (s for s, _, _ in data)))\n mean_story_size = int(np.mean([ len(s) for s, _, _ in data ]))\n self.sentence_size = max(map(len, chain.from_iterable(s for s, _, _ in data)))\n self.candidate_sentence_size = max(map(len,candidates))\n query_size = max(map(len, (q for _, q, _ in data)))\n self.memory_size = min(self.memory_size, max_story_size)\n self.vocab_size = len(self.word_idx) + 1 # +1 for nil word\n self.sentence_size = max(query_size, self.sentence_size) # for the position\n\n # params\n print(\"vocab size:\",self.vocab_size)\n print(\"Longest sentence length\", self.sentence_size)\n print(\"Longest candidate sentence length\", self.candidate_sentence_size)\n print(\"Longest story length\", max_story_size)\n print(\"Average story length\", mean_story_size)\n\n if save:\n with open(save, 'wb') as vocab_file:\n pickle.dump(vocab, vocab_file)\n \n def train(self):\n \"\"\"\n Training method for the chatbot. It is based on `self.trainData`, on side-effect values\n from `build_vocab`, and potentially other class' attributes.\n\n An epoch corresponds to one training on the whole dataset. If the current epoch's number\n is divisible by `self.evaluation_interval` (or that we're at the last epoch), the training\n and validating accuracies are computed, printed/stored. Furthermore, if the validation\n accuracy is the best in comparison to the previous values, the model is serialized.\n \"\"\"\n trainP, trainS, trainQ, trainA = vectorize_data(self.trainData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n valP, valS, valQ, valA = vectorize_data(self.valData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n n_train = len(trainS)\n n_val = len(valS)\n print(\"Training Size\",n_train)\n print(\"Validation Size\", n_val)\n tf.set_random_seed(self.random_state)\n batches = zip(range(0, n_train-self.batch_size, self.batch_size), range(self.batch_size, n_train, self.batch_size))\n batches = [(start, end) for start, end in batches]\n best_validation_accuracy=0\n\n print('Number of epochs:', self.epochs)\n for t in range(1, self.epochs+1):\n print('Epoch', t)\n np.random.shuffle(batches)\n total_cost = 0.0\n for start, end in batches:\n p = trainP[start:end]\n s = trainS[start:end]\n q = trainQ[start:end]\n a = trainA[start:end]\n cost_t = self.model.batch_fit(p, s, q, a)\n total_cost += cost_t\n if t % self.evaluation_interval == 0 or t == self.epochs:\n print('validation')\n print('predicting training full dataset...')\n train_preds=self.model.batch_predict(trainP, trainS, trainQ)\n print('predicting validation full dataset...')\n val_preds=self.model.batch_predict(valP, valS,valQ)\n print('finished predictions.')\n train_acc = metrics.accuracy_score(np.array(train_preds), trainA)\n val_acc = metrics.accuracy_score(val_preds, valA)\n print('-----------------------')\n print('Epoch', t)\n print('Total Cost:', total_cost)\n print('Training Accuracy:', train_acc)\n print('Validation Accuracy:', val_acc)\n print('-----------------------')\n\n # write summary\n # train_acc_summary = tf.scalar_summary('task_' + str(self.task_id) + '/' + 'train_acc', tf.constant((train_acc), dtype=tf.float32))\n # val_acc_summary = tf.scalar_summary('task_' + str(self.task_id) + '/' + 'val_acc', tf.constant((val_acc), dtype=tf.float32))\n # merged_summary = tf.merge_summary([train_acc_summary, val_acc_summary])\n train_acc_summary = tf.summary.scalar('task_' + str(self.task_id) + '/' + 'train_acc', tf.constant((train_acc), dtype=tf.float32))\n val_acc_summary = tf.summary.scalar('task_' + str(self.task_id) + '/' + 'val_acc', tf.constant((val_acc), dtype=tf.float32))\n merged_summary = tf.summary.merge([train_acc_summary, val_acc_summary])\n summary_str = self.sess.run(merged_summary)\n self.summary_writer.add_summary(summary_str, t)\n self.summary_writer.flush()\n \n if val_acc > best_validation_accuracy:\n best_validation_accuracy=val_acc\n self.saver.save(self.sess, os.path.join(self.model_dir, \"model.ckpt\"),global_step=t)\n\n @classmethod\n def restore_model(cls, **kwargs):\n \"\"\"\n Helper class method which tries to construct a chatbot instance and restore\n the tensorflow's session. It can be used to recover a model from a previous\n training session.\n\n :param kwargs: Same arguments as `Chatbot.__init__`\n :return: The successfully restored model (if not successful, a `ValueError` is raised)\n \"\"\"\n ckpt = tf.train.get_checkpoint_state(kwargs['model_dir'])\n\n if ckpt and ckpt.model_checkpoint_path:\n created_cb = cls(**kwargs)\n created_cb.saver.restore(created_cb.sess, ckpt.model_checkpoint_path)\n else:\n raise ValueError(\"`model_dir` does not exist or was not created correctly\")\n\n return created_cb\n\n def test(self):\n \"\"\"\n Load a model from a previous training session and prints the accuracy for\n the testing dataset.\n \"\"\"\n ckpt = tf.train.get_checkpoint_state(self.model_dir)\n if ckpt and ckpt.model_checkpoint_path:\n self.saver.restore(self.sess, ckpt.model_checkpoint_path)\n else:\n print(\"...no checkpoint found...\")\n if self.isInteractive:\n self.interactive()\n else:\n testP, testS, testQ, testA = vectorize_data(self.testData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n n_test = len(testS)\n print(\"Testing Size\", n_test)\n test_preds=self.model.batch_predict(testP, testS,testQ)\n test_acc = metrics.accuracy_score(test_preds, testA)\n print(\"Testing Accuracy:\", test_acc)\n \n # print(testA)\n # for pred in test_preds:\n # print(pred, self.indx2candid[pred])\n\n def test_accuracy(self, test_data_dir):\n \"\"\"\n Compute and return the testing accuracy for the data directory given in argument.\n It is a more general method than `Chatbot.test` as it can be used on different\n datasets than the one given at initialisation.\n\n :param test_data_dir: Directory's path where to find the testing dataset\n :return: The accuracy score for the testing file\n \"\"\"\n _, testData, _ = load_dialog_task(test_data_dir, self.task_id, self.candid2indx, self.OOV)\n testP, testS, testQ, testA = vectorize_data(testData, self.word_idx, self.sentence_size, self.batch_size, self.n_cand, self.memory_size, self._profiles_mapping)\n test_preds = self.model.batch_predict(testP, testS, testQ)\n test_acc = metrics.accuracy_score(test_preds, testA)\n\n return test_acc\n\n def close_session(self):\n \"\"\"Helper function to close the owned attributes (i.e. the tensorflow's session)\"\"\"\n self.sess.close()\n\n\ndef run_experiment(experiment_path, test_dirs, **kwargs):\n \"\"\"\n Helper function for running experiment. The main purpose is to document\n the experiment and to ensure that the information is clearly established.\n\n\n Args:\n - experiment_path: directory for the experiment (created if not exist)\n - test_dirs: list of directories for to take the testing data from, and evaluating it\n - kwargs can also contains any other argument that will be given to ChatBot.\n \"\"\"\n os.makedirs(experiment_path, exist_ok=True)\n\n model_dir = experiment_path\n vocabulary = os.path.join(experiment_path, 'vocabulary.obj')\n profiles = os.path.join(experiment_path, 'profiles.obj')\n\n kwargs['model_dir'] = model_dir\n\n kwargs_load = kwargs.copy()\n kwargs_load['load_vocab'] = vocabulary\n kwargs_load['load_profiles'] = profiles\n\n kwargs_save = kwargs.copy()\n kwargs_save['save_vocab'] = vocabulary\n kwargs_save['save_profiles'] = profiles\n\n try:\n chatbot = ChatBot.restore_model(**kwargs_load)\n except Exception as err:\n print('Did not load, generate:', err)\n\n with open(os.path.join(experiment_path, 'attributes.log'), 'w') as f:\n pprint.pprint(kwargs, stream=f, indent=4)\n\n tf.reset_default_graph()\n chatbot = ChatBot(**kwargs_save)\n chatbot.train()\n\n for test_dir in test_dirs:\n acc = chatbot.test_accuracy(test_dir)\n print('Accuracy for {}: {:.5%}'.format(test_dir, acc))\n\n chatbot.close_session()\n\n\nif __name__ =='__main__':\n model_dir=\"tmp/task\"+str(FLAGS.task_id)+\"_\"+FLAGS.model_dir\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\n\n if FLAGS.interactive:\n test_dirs = glob.glob('../data/personalized-dialog-dataset/split-by-profile/*')\n test_dirs = list(test_dirs)\n small_train_dataset = '../data/personalized-dialog-dataset/small'\n\n from IPython import embed\n pp = pprint.PrettyPrinter(indent=4)\n embed()\n\n else:\n # chatbot.run()\n if FLAGS.experiment == \"test\":\n run_experiment('experiments/test',\n ['../data/personalized-dialog-dataset/split-by-profile/female_elderly'],\n data_dir='../data/personalized-dialog-dataset/small',\n task_id=5,\n epochs=3)\n elif FLAGS.experiment == \"full_profile\":\n test_dirs = glob.glob('../data/personalized-dialog-dataset/split-by-profile/*')\n test_dirs = list(test_dirs)\n\n run_experiment('experiments/full_profile',\n test_dirs,\n data_dir='../data/personalized-dialog-dataset/small',\n task_id=5,\n epochs=200)\n\n elif FLAGS.experiment == 'split-by-profile':\n test_dirs = glob.glob('../data/personalized-dialog-dataset/split-by-profile/*')\n test_dirs = [f for f in test_dirs if os.path.isdir(f)]\n\n run_experiment('experiments/split_by_profile',\n test_dirs,\n data_dir='../data/personalized-dialog-dataset/merged-from-split-by-profile',\n task_id=5,\n epochs=200)\n\n else:\n chatbot=ChatBot(FLAGS.data_dir,\n model_dir,\n FLAGS.task_id,\n OOV=FLAGS.OOV,\n isInteractive=FLAGS.interactive,\n batch_size=FLAGS.batch_size,\n memory_size=FLAGS.memory_size,\n save_vocab=FLAGS.save_vocab,\n load_vocab=FLAGS.load_vocab,\n epochs=FLAGS.epochs,\n evaluation_interval=FLAGS.evaluation_interval,\n verbose=FLAGS.verbose,\n alpha=FLAGS.alpha)\n\n if FLAGS.train:\n chatbot.train()\n else:\n chatbot.test()\n\n chatbot.close_session()\n","sub_path":"MemN2N-mtl-more-softmax/single_dialog.py","file_name":"single_dialog.py","file_ext":"py","file_size_in_byte":19178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"267730778","text":"import csv\nimport math\nimport numpy as np\nimport random\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\nx=[]\ny=[]\nfreq1=[20,210,30,0,-1,1,1]\nfreq2=[20,0,1.9,25,58,7]\nfreq3=[1,2,3,4,5]\nfreq4=[600,1000,3,4]\ncost1=[3000,5000,6000,2500,1500,2000,1000,1500]\ncost2=[3000,1500,4000,7000,5000,4600]\ncost3=[1700,2500,1300,3400,1500]\ncost4=[7100,4200,3700,4000]\nlis1=[]\nlis2=[]\ncar={}\nhead=['T1','T2','T3','T4','T5','T6','T7','T8','T9','T10','CAR_ID','ATTRIBUTE']\ncl=['Car1','Car2','Car3','Car4','Car5','Car6','Car7','Car8','Car9','Car10','Car11','Car12','Car13','Car14','Car15']\n\ndef immediate(dataset):\n\tdataset = csv.reader(open(dataset, newline=''), delimiter= \" \", quotechar=\"|\")\n\ti=0\n\tprob=' '\n\ts=0\n\t#wq=0\n\tk=0\n\ttot=0\n\trow=['0','0','0','0','0','0','0','0','0','0','0']\n\tprev=[' ',' ',' ',' ',' ',' ',' ']\n\t#inp=input(\"attribute\")\n\tfor row in dataset:\n\n\t\ts=s+1\n\t\tif(i<=0):\n\t\t\theader=row[0].split(',')\n\t\t\theader.append(' ')\n\t\t\theader.append(' ')\n\t\t\ti=i+1\n\t\t\ts=0\n\t\telse:\n\t\t\trow=row[0].split(',')\n\t\t\tnow=[row[1],row[1],row[1],row[1],row[1],row[1],row[1]]\n\n\t\t\t\t\t\t#0 to 3 years\n\t\t\t#engine oil checking\n\t\t\tif(header[3]=='ENGINE_OIL' and int(row[3])<=freq1[0] and (now[0]==' ' or now[0]!=prev[0])):\n\t\t\t\tprob= header[3]+', '\n\t\t\t\ttot=tot+cost1[0]\n\t\t\t\tprev[0]=row[1]\n\n\t\t\t#coolant checking\n\t\t\tif(header[4]=='COOLANT' and int(row[4])>=freq1[1] and (now[1]==' ' or now[1]!=prev[1])):\n\t\t\t\tprob= prob + ' ' + header[4]\n\t\t\t\ttot=tot+cost1[1]\n\t\t\t\tprev[1]=row[1]\n\n\t\t\tif(header[5]=='BATTERY' ):\n\t\t\t\tif(k<120):\n\t\t\t\t\tx.append(int(row[5]))\n\t\t\t\t\tk=k+1\n\n\t\t\t#battery checking\n\t\t\tif(header[5]=='BATTERY' and int(row[5])<=freq1[2] and (now[2]==' ' or now[2]!=prev[2])):\n\t\t\t\tprob= prob + ' ' + header[5]\n\t\t\t\ttot=tot+cost1[2]\n\t\t\t\tprev[2]=row[1]\n\n\t\t\t#lights checking\n\t\t\tif(header[6]=='LIGHTS' and int(row[6])<=freq1[3] and (now[3]==' ' or now[3]!=prev[3])):\n\t\t\t\tprob=prob +' ' + header[6]\n\t\t\t\ttot=tot+cost1[3]\n\t\t\t\tprev[3]=row[1]\n\n\t\t\t#left wheel alignment checking\n\t\t\tif(header[7]=='WHEEL_ALIGNMENT' and int(row[7])<=freq1[4] and (now[4]==' ' or now[4]!=prev[4])):\n\t\t\t\tprob=prob +' left-' + header[7]\n\t\t\t\ttot=tot+cost1[4]\n\t\t\t\tprev[4]=row[1]\n\n\t\t\t#right wheel alignment checking\n\t\t\tif(header[7]=='WHEEL_ALIGNMENT' and int(row[7])>=freq1[5] and (now[4]==' ' or now[4]!=prev[4])):\n\t\t\t\tprob=prob + ' right-' + header[7]\n\t\t\t\ttot=tot+cost1[4]\n\t\t\t\tprev[4]=row[1]\n\n\t\t\t#cleaning\n\t\t\tif(header[8]=='CLEANING' and int(row[8])>=freq1[6] and (now[5]==' ' or now[5]!=prev[5])):\n\t\t\t\tprob=prob + ' '+ header[8]\n\t\t\t\ttot=tot+cost1[5]\n\t\t\t\tprev[5]=row[1]\n\n\t\t\t#oil filter checking\n\t\t\tif(header[9]=='OIL_FILTER' and row[9]=='yes' and (now[6]==' ' or now[6]!=prev[6])):\n\t\t\t\tprob=prob+ ' ' + header[9]\n\t\t\t\ttot=tot+cost1[6]\n\t\t\t\tprev[6]=row[1]\n\n\t\t\t\t\t\t\t#3 to 6 years\n\t\t\t#rad check\n\t\t\tif(header[3]=='RAD_CHECK' and int(row[3])=freq3[0] and (now[0]==' ' or now[0]!=prev[0])):\n\t\t\t\tprob=prob+ ' ' + header[3]\n\t\t\t\ttot=tot+cost3[0]\n\t\t\t\tprev[0]=row[1]\n\n\t\t\t#fuel ejectors checking\n\t\t\tif(header[4]=='FUEL_EJECTORS' and int(row[4])>=freq3[1] and (now[1]==' ' or now[1]!=prev[1])):\n prob=prob+ ' ' + header[4]\n tot=tot+cost3[1]\n prev[1]=row[1]\n\n\t\t\t#power steering check\n\t\t\tif(header[5]=='POWER_STEERING_FUEL' and int(row[5])>=freq3[2] and (now[2]==' ' or now[2]!=prev[2])):\n prob=prob+ ' ' + header[5]\n tot=tot+cost3[2]\n prev[2]=row[1]\n\n\t\t\t#pcv valve check\n\t\t\tif(header[6]=='PCV_VALVE' and int(row[6])>=freq3[3] and (now[3]==' ' or now[3]!=prev[3])):\n prob=prob+ ' ' + header[6]\n tot=tot+cost3[3]\n prev[3]=row[1]\n\n\t\t\t#transmission checking\n\t\t\tif(header[7]=='TRANSMISSION' and int(row[7])>=freq3[4] and (now[4]==' ' or now[4]!=prev[4])):\n prob=prob+ ' ' + header[7]\n tot=tot+cost3[4]\n prev[4]=row[1]\n\n\t\t\t\t\t\t\t#9 to 15 years\n\n\t\t\t#seat belts\n\t\t\tif(header[3]=='SEAT_BELTS' and int(row[3])>=freq4[1] and int(row[3])<=freq4[0] and (now[0]==' ' or now[0]!=prev[0])):\n prob=prob+ ' ' + header[3]\n tot=tot+cost4[0]\n prev[0]=row[1]\n\n\t\t\t#engine idle settings\n\t\t\tif(header[4]=='ENGINE_IDLE' and int(row[4])>=freq4[2] and (now[1]==' ' or now[1]!=prev[1])):\n prob=prob+ ' ' + header[4]\n tot=tot+cost4[1]\n prev[1]=row[1]\n\n\t\t\t#clutch plate\n\t\t\tif(header[5]=='CLUTCH' and int(row[5])>=freq4[3] and (now[2]==' ' or now[2]!=prev[2])):\n prob=prob+ ' ' + header[5]\n tot=tot+cost4[2]\n prev[2]=row[1]\n\n\t\t\t#water pump\n\t\t\tif(header[6]=='TRANSMISSION' and int(row[6])>=freq4[4] and (now[3]==' ' or now[3]!=prev[3])):\n prob=prob+ ' ' + header[6]\n tot=tot+cost4[3]\n prev[3]=row[1]\n\t\t\n\t\t\tro=row[1]\n\t\t\tif(s>=12):\n\t\t\t\ts=0\n\t\t\t\tif(tot>0):\n\t\t\t\t\tprob1=row[0] + ' has a problems in '+ prob+ ' in ' + ro + ' of total cost RS.' +str(tot)\n\t\t\t\t\tprint(prob1)\n\t\t\t\t\tprint('\\n')\n\t\t\t\t\tch=input()\n\t\t\t\t\tif(ch=='\\0'):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\ttot=0\n\t\t\t\t\tprob1=' '\n\t\t\t\tprob=' '\n\t\t\t\tif(k>=120):\n\t\t\t\t\tgraph(x)\n\t\t\t\t\tk=12\n\t\t\t\t\tx.clear()\n\n\n\n\n\n\n\n\n\n\ndef graph(x):\n\tstyle.use('ggplot')\n\ti=0\n\tfor p in range(0,140):\n\t\ty.append(p)\n\tfor l in x:\n\t\tif(l>=30):\n\t\t\tplt.bar(y[i],l,width= 1.3,color=\"red\")\n\t\telse:\n\t\t\tplt.bar(y[i],l,width=1.3,color=\"green\")\n\t\ti=i+1\n\n\tplt.ylim(0,250)\n\tplt.xlim(0,150)\n\tplt.title('TRIPS')\n\tplt.xlabel('TIME')\n\tplt.ylabel('ATTRIBUTE')\n\tplt.show()\n\ty.clear()\n\n\npath='dataset1.csv'\nprint('information for 0-3 years\\n')\nimmediate(path)\n#future(path,freq2)","sub_path":"immediate.py","file_name":"immediate.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"37520210","text":"\"\"\"Модуль генерации изображений заглушек\"\"\"\n\nimport os\nimport pathlib\n\nfrom PIL import Image, ImageDraw, ImageFont\nfrom flask import send_file, current_app, request\n\nfrom . import canvas\n\n\n@canvas.route('/', methods=['GET', 'POST'])\n@canvas.route('/', methods=['GET', 'POST'])\n@canvas.route('/x', methods=['GET', 'POST'])\ndef main(width=None, height=None):\n \"\"\"Обработка запросов на генерацию изображения\"\"\"\n # Подготовка данных\n width = width or 480\n height = height or width\n maximum = 3840\n width = width if width < maximum else maximum\n height = height if height < maximum else maximum\n\n color = request.args.get('c') or 'cccccc'\n if len(color) == 3:\n color += color\n try:\n rgb = tuple(int(color[i:i + 2], 16) for i in (0, 2, 4))\n except ValueError:\n color = 'cccccc'\n rgb = (204, 204, 204)\n\n # Формирование PATH и NAME\n name = f'{width}x{height}.jpg'\n directory = os.path.join(current_app.config['STORAGE'], 'canvas', color.lower())\n path = os.path.join(directory, name)\n try:\n # Поиск в ранее сгенерированных файлов\n return send_file(path)\n except FileNotFoundError:\n # Формирование изображения\n img = Image.new('RGB', (width, height), rgb)\n rgb = tuple(350 - i for i in rgb)\n if width >= 50 and height >= 50:\n draw = ImageDraw.Draw(img)\n # Расчет размера шрифта\n font_size = 12\n txt = f'{width}x{height}'\n basedir = os.path.abspath(os.path.dirname(__file__))\n font_path = os.path.join(basedir, 'roboto.ttf')\n while True:\n font = ImageFont.truetype(font_path, font_size)\n tw, th = draw.textsize(txt, font)\n if tw > img.width * 0.5 or th > img.height * 0.5:\n break\n font_size += 1\n # Печать размера изображения\n font = ImageFont.truetype(font_path, font_size)\n tw, th = draw.textsize(txt, font)\n position = (img.width / 2 - tw / 2, img.height / 2 - th / 1.7)\n draw.text(position, txt, rgb, font=font)\n # Печать логотипа\n if width / height <= 2 and width >= 100:\n txt = 'LOGGER.SU'\n font = ImageFont.truetype(font_path, int(font_size / 2))\n tw, th = draw.textsize(txt, font=font)\n position = (int(th / 2), img.height - th - int(th / 2))\n draw.text(position, txt, rgb, font=font)\n del draw\n # Сохранение изображения\n pathlib.Path(directory).mkdir(parents=True, exist_ok=True)\n img.save(path)\n return send_file(path)\n","sub_path":"app/canvas/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"183375065","text":"interpolations = []\n\n\nclass Linear:\n def __init__(self):\n self.interpolator = CubicBezier(0, 0, 1, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass Interpolation:\n \"\"\"Gère les interpolations des valeurs.\n Permet d'utiliser une fonction de type cubic bezier (http://cubic-bezier.com) pour intérpoler les valeurs.\"\"\"\n\n def __init__(self, start, stop, milliseconds: int, callback, method=Linear, args=()):\n self.startValue = type(start)(start) # Use the copy constructor, workaround for copy.copy()\n self.stopValue = type(stop)(stop)\n\n self.milliseconds = milliseconds\n self.method = method\n self.args = args\n self.callback = callback\n\n self.generator = self.Generator()\n self.paused = False\n\n def Generator(self):\n interpolator = self.method(*self.args)\n\n seconds = self.milliseconds / 1000.0\n diff = self.stopValue - self.startValue\n inc = 1.0 / 60 # pygame.time.Clock.get_fps()\n progression = self.startValue * 0\n current_second = inc\n\n while current_second < seconds:\n percent = 1 - ((seconds - current_second)) / seconds\n\n previous_step = progression\n progression = diff * interpolator.ease(percent)\n\n yield (self.startValue + progression, progression - previous_step)\n current_second += inc\n\n yield (self.stopValue, self.stopValue - (self.startValue + progression))\n\n def start(self):\n self.resume()\n if self not in interpolations:\n interpolations.append(self)\n return self\n\n def stop(self):\n if self in interpolations:\n interpolations.remove(self)\n\n def pause(self):\n self.paused = True\n\n def resume(self):\n self.paused = False\n\n def interpolate(self):\n if not self.paused:\n try:\n self.callback(*next(self.generator))\n except StopIteration:\n interpolations.remove(self)\n\n\ndef updateInterpolations():\n for interpolation in interpolations:\n interpolation.interpolate()\n\n\n\n\n# Predefined Cubic Bezier classes\nclass Ease:\n def __init__(self):\n self.interpolator = CubicBezier(.25, .1, .25, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass EaseIn:\n def __init__(self):\n self.interpolator = CubicBezier(.42, 0, 1, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass EaseOut:\n def __init__(self):\n self.interpolator = CubicBezier(0, 0, .58, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\nclass EaseInOut:\n def __init__(self):\n self.interpolator = CubicBezier(.42, 0, .58, 1)\n\n def ease(self, t):\n return self.interpolator.ease(t)\n\n\n# Un grand merci pour https://github.com/gre/bezier-easing/blob/master/src/index.js\n# Librairie js qui implémente Cubic Bezier, souvent utilisé pour créer des animations en CSS\nclass CubicBezier:\n NEWTON_ITERATIONS = 4\n NEWTON_MIN_SLOPE = 0.001\n SUBDIVISION_PRECISION = 0.0000001\n SUBDIVISION_MAX_ITERATIONS = 10\n\n kSplineTableSize = 11\n kSampleStepSize = 1.0 / (kSplineTableSize - 1.0)\n\n def __init__(self, x1, y1, x2, y2):\n if not (0 <= x1 <= 1 and 0 <= x2 <= 1):\n raise RuntimeError(\"bezier x values must be in [0, 1] range\")\n\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n\n self.sampleValues = []\n if self.x1 != self.y1 or self.x2 != self.y2:\n for i in range(self.kSplineTableSize):\n self.sampleValues.append(self.calcBezier(i * self.kSampleStepSize, self.x1, self.x2))\n\n def ease(self, t):\n if self.x1 == self.y1 and self.x2 == self.y2:\n return t\n\n if t == 0:\n return 0\n if t == 1:\n return 1\n\n return self.calcBezier(self.getTForX(t), self.y1, self.y2)\n\n def getTForX(self, aX):\n intervalStart = 0.0\n currentSample = 1\n lastSample = self.kSplineTableSize - 1\n\n while currentSample != lastSample and self.sampleValues[currentSample] <= aX:\n intervalStart += self.kSampleStepSize\n currentSample += 1\n currentSample -= 1\n\n dist = (aX - self.sampleValues[currentSample]) / (\n self.sampleValues[currentSample + 1] - self.sampleValues[currentSample])\n guessForT = intervalStart + dist * self.kSampleStepSize\n\n initialSlope = self.getSlope(guessForT, self.x1, self.x2)\n if initialSlope >= self.NEWTON_MIN_SLOPE:\n return self.newtonRaphsonIterate(aX, guessForT, self.x1, self.x2)\n\n elif initialSlope == 0:\n return guessForT\n\n else:\n return self.binarySubdivide(aX, intervalStart, intervalStart + self.kSampleStepSize, self.x1, self.x2)\n\n @classmethod\n def A(cls, aA1, aA2):\n return 1.0 - 3.0 * aA2 + 3.0 * aA1\n\n @classmethod\n def B(cls, aA1, aA2):\n return 3.0 * aA2 - 6.0 * aA1\n\n @classmethod\n def C(cls, aA1):\n return 3.0 * aA1\n\n @classmethod\n def calcBezier(cls, aT, aA1, aA2):\n return ((cls.A(aA1, aA2) * aT + cls.B(aA1, aA2)) * aT + cls.C(aA1)) * aT\n\n @classmethod\n def getSlope(cls, aT, aA1, aA2):\n return 3.0 * cls.A(aA1, aA2) * aT * aT + 2.0 * cls.B(aA1, aA2) * aT + cls.C(aA1)\n\n @classmethod\n def binarySubdivide(cls, aX, aA, aB, mX1, mX2):\n currentX = 0\n currentT = 0\n i = 0\n\n firstTime = True\n\n while firstTime or (abs(currentX) > cls.SUBDIVISION_PRECISION and i < cls.SUBDIVISION_MAX_ITERATIONS):\n currentT = aA + (aB - aA) / 2.0\n currentX = cls.calcBezier(currentT, mX1, mX2) - aX\n if currentX > 0:\n aB = currentT\n else:\n aA = currentT\n\n i += 1\n firstTime = False\n\n return currentT\n\n @classmethod\n def newtonRaphsonIterate(cls, aX, aGuessT, mX1, mX2):\n for i in range(cls.NEWTON_ITERATIONS):\n currentSlope = cls.getSlope(aGuessT, mX1, mX2)\n if currentSlope == 0:\n return aGuessT\n\n currentX = cls.calcBezier(aGuessT, mX1, mX2) - aX\n aGuessT -= currentX / currentSlope\n\n return aGuessT\n","sub_path":"gameengine/core/Interpolation.py","file_name":"Interpolation.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"92373004","text":"from ..models.survey import Survey, SurveySection, SurveyQuest, SurveyQuestOptions, SurveyBrief, AutoIds, SurveyResponse, SurveyInvitation\nfrom mongoalchemy.fields import *\nfrom .kafkadao import KafkaDao as kafka\nfrom datetime import datetime\nfrom flask import jsonify\nimport json\nimport traceback\nfrom loggers import *\nlogger = createLogger(__name__)\n\nclass SurveyDao():\n def __init__(self):\n pass\n\n def getSingleSurvey(self, id):\n from bson import json_util\n try:\n survey = Survey.query.filter_by(id=int(id)).first()\n result = json.dumps(survey, default=survey.encode_model)\n return result\n except Exception:\n traceback.print_exc()\n raise Exception\n\n def createSurvey(self, data, db):\n surveySections = []\n for section in data.get('sections'):\n questions = []\n for question in section.get('questions'):\n q = SurveyQuest(qid = self.autoId('question_id'), name = question.get('name'), type = question.get('type'), options = question.get('options'))\n questions.append( q )\t\n s = SurveySection(section_id = self.autoId('section_id'), name= section.get('name'), questions = questions) \n surveySections.append( s )\n survey = Survey(id=self.autoId('survey'),name = data.get('name'), sections = surveySections)\n try:\n db.session.add(survey)\n sr = SurveyBrief(id=survey.id, name = survey.name, start_date = survey.start_date) \n db.session.add(sr)\n db.session.flush()\n response = None\n return response\n except Exception:\n traceback.print_exc()\n raise Exception\n\n def getSurvey(self):\n from bson import json_util\n try:\n surveys = SurveyBrief.query.all()\n l = [json.dumps(ob, default=ob.encode_model) for ob in surveys]\n return l\n except Exception:\n traceback.print_exc()\n raise Exception\n\n def autoId(self, name):\n from bson import json_util \n try:\n ids = AutoIds.query.filter_by(id=name).first()\n id = ids.sequence_value + 1\n ids.sequence_value = id\n ids.save()\n return id\n except AttributeError:\n auto_id = AutoIds(id=name, sequence_value=1)\n auto_id.save()\n return 1\n except Exception:\n traceback.print_exc()\n\n def sendSurveyLink(self, data, db):\n import re\n regex = re.compile(r\"href=[\\'\\\"]?([^\\'\\\" >]+)\")\n survey_name = data.get('survey_name')\n survey_id = data.get('survey_id')\n survey_oid = data.get('survey_identifier')\n userList = data.get('selected_users')\n url = data.get('url')\n cm = data.get('message')\n messages = []\n for user in userList:\n link = url+\"/\"+survey_oid+\"/\"+survey_id+\"/\"+user.get('userId')\n message = {}\n message['chat_id'] = user.get('userId')\n message['messageType'] = 'outgoing'\n message['userMessage'] = None\n message['text'] = cm+'\\n\\n\\nTake Survey '\n messages.append(message)\n sent_on = []\n try:\n for message in messages:\n kafka.publish(message = message)\n f = re.search(regex, message.get('text'))\n if self.checkForExistingInvitation(survey_id=int(survey_id), user_id=message.get('chat_id')) >= 1:\n inviation = SurveyInvitation.query.filter_by(survey_id=int(survey_id), user_id=message.get('chat_id')).first()\n sent_on = inviation.sent_on\n sent_on.append(datetime.now())\n inviation.save()\n else:\n survey_invitation = SurveyInvitation(survey_id=int(survey_id) , survey_name=survey_name, survey_link=f.group(1), message=cm, user_id=message.get('chat_id'), sent_on = [datetime.now()])\n db.session.add(survey_invitation)\t\t\n except Exception:\n traceback.print_exc()\n raise Exception\n\t \n def checkForExistingInvitation(self,survey_id, user_id):\n try:\n inviation = SurveyInvitation.query.filter_by(survey_id=int(survey_id), user_id=user_id).count()\n return inviation\n except Exception:\n traceback.print_exc()\n raise Exception\n\t \n ''' Save the survey response '''\n def saveSurveyResponse(self, data, db):\n survey_response = SurveyResponse(id = self.autoId(\"survey_response_id\"), survey_id = int(data.get('survey_id')), survey_name = data.get('survey_name'), user_id = data.get('user_id'), sections = data.get('sections'))\n try:\n db.session.add(survey_response)\n survey_brief = SurveyBrief.query.filter_by(id = int(data.get('survey_id'))).first()\n vote = survey_brief.votes + 1\n survey_brief.votes = vote\n survey_brief.save()\n db.session.flush()\n response = {}\n response['message'] = \"You have successfully completed the survey. Thank you.\"\n return response\n except Exception:\n traceback.print_exc()\n raise Exception\n\t \n ''' Validate if user has already submitted the survey response '''\n def checkSurveyResponseExist(self, user_id, survey_id):\n try:\n doc = SurveyResponse.query.filter_by(survey_id = int(survey_id), user_id = user_id).count()\n if doc == 1:\n return True\n else:\n return False\n except Exception:\n traceback.print_exc()\n raise Exception\t \n","sub_path":"bot/application/dao/surveydao.py","file_name":"surveydao.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"488239679","text":"# __author__ = 'Administrator'\r\n# coding: utf-8\r\n\r\nimport os\r\n\r\nfrom PIL import Image, ImageDraw, ImageFont\r\n\r\n\r\nfontsize = 23\r\nfonttype = u'msyh.ttf'\r\ncolor = (255, 240, 241)\r\n\r\n\r\ndef watermark(filepath, string):\r\n '''在文件同级目录创建图片的水印图片'''\r\n ima = Image.open(filepath)\r\n x, y = ima.size\r\n font = ImageFont.truetype(fonttype, fontsize)\r\n draw = ImageDraw.Draw(ima)\r\n xr, yr = draw.textsize(string, font=font)\r\n if xr >= x or yr >= y:\r\n rate = xr / x + 1 if xr / x > 0 else yr / y + 1\r\n font = ImageFont.truetype(fonttype, fontsize / rate)\r\n xr, yr = draw.textsize(string, font=font)\r\n draw.text((x - xr, y - yr), string, font=font, fill=color)\r\n ##draw.bitmap(xy, bitmap, options)\r\n f1, ff = os.path.splitext(filepath)\r\n newfilepath = u'%s%s%s' % (f1, u'_watermark', ff)\r\n ima.save(newfilepath)","sub_path":"demo/common/utils/watermark.py","file_name":"watermark.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"70086567","text":"import pickle\nimport numpy as np\nimport cv2\n\n\ndef draw_bbox(img, rects):\n im = img.copy()\n for r in rects:\n xmin, ymin, xmax, ymax = r\n col = (255, 0, 0)\n cv2.rectangle(im, (xmin, ymin), (xmax, ymax), tuple(col), 2)\n return im\n\n\nPICKLEPATH = '../../../data/wider_face/train_bbox_annotations_with_splits.pkl'\nIMAGEDIR = '../../../data/wider_face/'\n\nwith open(PICKLEPATH, 'rb') as f:\n ants = pickle.load(f)\n\n\n\n\n\n\nfor ind, a in enumerate(ants):\n bbox = a['ann']['bboxes']\n valid = (bbox[:,2] > bbox[:,0]) and (bbox[:,3] > bbox[:,1])\n if np.sum(valid) != len(bbox):\n print ('Invalid bbox annotation detected ...')\n print ('Removing !')\n ants[ind]['ann']['bboxes'] = bbox[valid]\n ants[ind]['ann']['labels'] = a['ann']['labels'][valid]\n assert len(ants[ind]['ann']['bboxes']) == len(ants[ind]['ann']['labels'])\n\nwith open(PICKLEPATH, 'wb') as f:\n pickle.dump(ants, f)","sub_path":"src/etl/3_visualize_bbox_annotations.py","file_name":"3_visualize_bbox_annotations.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"500221762","text":"import matplotlib.pyplot as plt, mpld3\nfrom matplotlib import pyplot, transforms\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nfrom matplotlib.patches import Ellipse\nimport pandas as pd\nimport datetime as dt\n\n\ndef grafica(year):\n r_earth = 6371\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]\n x = r_earth*np.cos(u)*np.sin(v)\n y = r_earth*np.sin(u)*np.sin(v)\n z = r_earth*np.cos(v)\n ax.plot_wireframe(x, y, z, color=\"b\",alpha=0.1)\n ax.set_xlim(-50000, 50000)\n ax.set_ylim(-50000, 50000)\n ax.set_zlim(-50000, 50000)\n\n data=pd.read_json(\"Data/satcat.json\")\n final=int(year)\n inicio=int(final)-5\n\n\n data_filter=data.loc[(data['LAUNCH_YEAR']>=inicio)&(data['LAUNCH_YEAR']<=final),['INCLINATION','PERIGEE','APOGEE','LAUNCH_YEAR']]\n\n\n for ind in data_filter.index:\n ang = data_filter['INCLINATION'][ind]\n perigee = data_filter['PERIGEE'][ind]\n apogee = data_filter['APOGEE'][ind]\n\n u_e = np.linspace(0, 2*np.pi, 100)\n h = 362\n a = (perigee + apogee + 2*r_earth)/2\n c = a - (perigee + r_earth)\n ecc = c / a\n b = np.sqrt(pow(a,2)*(1-pow(ecc,2)))\n x_e = h + a * np.cos(u_e)\n y_e = b * np.sin(u_e)\n\n base = pyplot.gca().transData\n rot = transforms.Affine2D().rotate_deg(ang)\n\n ax.plot(x_e, y_e, 'r',alpha=0.1, transform = rot + base)\n\n fig.patch.set_facecolor('xkcd:black')\n ax.set_facecolor('xkcd:black')\n ax.grid(color='black')\n ax.tick_params(axis='x', colors='white')\n ax.tick_params(axis='y', colors='white')\n ax.tick_params(axis='z', colors='white')\n ax.view_init(elev=10., azim=180)\n plt.tight_layout()\n plt.savefig('image.png')\n # plt.show()\n #print (mpld3.fig_to_html(plt.show()))\n print('Done')\n#grafica(1967)\n","sub_path":"Orbits_Graph.py","file_name":"Orbits_Graph.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"45299517","text":"import random\r\n\r\ndef jogar():\r\n print(\"*****************************\")\r\n print(\"***** ADIVINHE O NUMERO *****\")\r\n print(\"*****************************\")\r\n\r\n print(\"Escolha o nível de dificuldade :\")\r\n nivel = int(input(\"(1) Fácil (2) Médio (3) Difícil\\n\"))\r\n tentativas = 0\r\n rodada = 1\r\n\r\n if(nivel == 1):\r\n tentativas = 20\r\n elif(nivel == 2):\r\n tentativas = 10\r\n else:\r\n tentativas = 5\r\n\r\n numero_secreto = random.randrange(1, 101)\r\n\r\n print(\"Favor informar um número entre 1 e 100.\")\r\n while(rodada <= tentativas):\r\n print(\"-\" * 40)\r\n print(\"Tentativa {} de {}.\".format(rodada, tentativas))\r\n tentativa = int(input(\"Informe o número :\"))\r\n print(\"Você digitou :\", tentativa)\r\n\r\n acertou = tentativa == numero_secreto\r\n maior = tentativa > numero_secreto\r\n menor = tentativa < numero_secreto\r\n\r\n if(tentativa < 0 or tentativa > 100):\r\n print(\"Favor informar um número entre 1 e 100.\")\r\n continue\r\n\r\n if(acertou):\r\n print(\"Você acertou o número sorteado.\")\r\n break\r\n else:\r\n if(maior):\r\n print(\"Não foi dessa vez. O número informado é maior do que o número sorteado\")\r\n elif(menor):\r\n print(\"Não foi dessa vez. O número informado é menor do que o número sorteado\")\r\n rodada += 1\r\n print(\"Infelizmente você chegou ao final do jogo. O número secreto era {}.\".format(numero_secreto))\r\n print(\"Fim do Jogo\")\r\n\r\nif(__name__ == \"__main__\"):\r\n jogar()","sub_path":"adivinhacao.py","file_name":"adivinhacao.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"595950129","text":"import datetime as dt\nimport pandas as pd\nimport math\nimport copy\n\nfrom paul_resources import InformationTable\nfrom option_model.Distribution_Module import Distribution, Distribution_MultiIndex, float_to_event_distribution, \\\n float_to_volbeta_distribution\nfrom option_model.Option_Module import get_time_to_expiry\nfrom option_model.Timing_Module import event_prob_by_expiry\nimport logging\n\n# Logging Setup\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nformatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s', \"%m/%d/%Y %H:%M\")\n\nfile_handler = logging.FileHandler('event_instances.log')\nfile_handler.setLevel(logging.INFO)\nfile_handler.setFormatter(formatter)\n\n#stream_handler = logging.StreamHandler()\n\nlogger.addHandler(file_handler)\n#logger.addHandler(stream_handler)\n\nclass GeneralEvent(object):\n name = 'General Event'\n abbrev_name = 'GenEvent'\n timing = None\n instances = ['Event']\n #main_lever = 2.0\n\n def __init__(self, timing_descriptor = timing):\n self.timing_descriptor = timing_descriptor\n\n for cls in type(self).__mro__[0:-1]:\n cls.instances.append(self)\n \n if type(self).__name__ == 'GeneralEvent':\n logger.info(\"General Event Instantiated Successfully\")\n\n def __str__(self):\n return \"{}\".format(self.abbrev_name)\n\n def __repr__(self):\n return \"{}\".format(self.abbrev_name)\n\n\nclass Event(GeneralEvent):\n name = 'Event'\n abbrev_name = 'SysEvent'\n timing = None\n mult = 1.0\n \n def __init__(self,\n stock: 'str',\n event_input: 'float or distribution object' = None,\n timing_descriptor = timing,\n event_name = None,\n idio_mult = 1.0):\n super().__init__(timing_descriptor = timing_descriptor)\n self.event_input_value = event_input\n \n self.stock = stock\n \n if type(event_input) is int or type(event_input) is float:\n self.event_input = float_to_event_distribution(event_input)\n else:\n self.event_input = event_input\n \n #if timing_descriptor is None:\n # self.timing_descriptor = self.timing\n #self.timing_descriptor = timing_descriptor\n if event_name is None:\n self.event_name = self.abbrev_name\n else:\n self.event_name = event_name\n self.idio_mult = idio_mult\n\n logger.info(\"{} {} Instantiated Successfully\".format(self.stock, self.name))\n \n if type(self).__name__ == 'Event':\n logger.info(\"{} Systematic Event Instantiated Successfully\".format(self.stock))\n \n def __str__(self):\n return \"{} ({:.2f}% move)\".format(self.name, self.modeled_move*100)\n\n def __repr__(self):\n return \"{}\".format(self.event_name)\n #return \"{} ({})\".format(self.abbrev_name, self.stock)\n\n @property\n def event_input_distribution_df(self):\n return self.event_input.distribution_df\n\n @property\n def modeled_move(self):\n return self.get_distribution().mean_move\n\n def set_idio_mult(self, new_value):\n self.idio_mult = new_value\n\n def set_move_input(self, new_value):\n self.event_input = new_value\n\n def get_distribution(self, expiry = None, *args, **kwargs):\n event_by_expiry = event_prob_by_expiry(self.timing_descriptor, expiry)\n event_not_by_expiry = 1 - event_by_expiry\n\n distribution_df = copy.deepcopy(self.event_input_distribution_df)\n distribution_df.loc[:, 'Pct_Move'] *= self.mult*self.idio_mult\n distribution_df.loc[:, 'Relative_Price'] = distribution_df.loc[:, 'Pct_Move'] + 1\n distribution_df.loc[:, 'Prob'] *= event_by_expiry\n \n no_event_scenario = {'State': ['No_Event'],\n 'Prob': [event_not_by_expiry],\n 'Pct_Move': [0],\n 'Relative_Price': [1.0]}\n \n no_event_scenario = pd.DataFrame(no_event_scenario).set_index('State').loc[:, ['Prob', 'Pct_Move', 'Relative_Price']]\n \n distribution_df = distribution_df.append(no_event_scenario)\n return Distribution(distribution_df)\n\n @property\n def event_bid(self):\n return Event(self.stock,\n self.event_input*.9,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return Event(self.stock,\n self.event_input*1.1,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n @property\n def event_width(self):\n return self.event_ask.get_distribution().mean_move - self.event_bid.get_distribution().mean_move\n\nclass IdiosyncraticVol(Event):\n name = 'Idiosyncratic Vol'\n abbrev_name = 'Idio_Vol'\n timing = None\n mult = 1.0\n instances = []\n\n def __init__(self,\n stock: 'str',\n event_input: 'float',\n idio_mult = 1.0):\n super().__init__(stock, idio_mult = idio_mult)\n \n if type(event_input) is int or type(event_input) is float:\n self.event_input = float_to_volbeta_distribution(event_input)\n else:\n self.event_input = event_input\n logger.info(\"{} {} Instantiated Successfully\".format(self.stock, self.name))\n \n def get_distribution(self, expiry):\n time_to_expiry = get_time_to_expiry(expiry)\n distribution_df = copy.deepcopy(self.event_input_distribution_df)\n distribution_df.loc[:, 'Pct_Move'] *= self.mult*self.idio_mult*math.sqrt(time_to_expiry)\n distribution_df.loc[:, 'Relative_Price'] = distribution_df.loc[:, 'Pct_Move'] + 1\n return Distribution(distribution_df)\n\n @property\n def event_bid(self):\n return IdiosyncraticVol(self.stock,\n self.event_input*.95,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return IdiosyncraticVol(self.stock,\n self.event_input*1.05,\n self.idio_mult)\n\nclass SysEvt_PresElection(Event):\n name = 'U.S. Presidential Election'\n abbrev_name = 'Elec.'\n timing = dt.date(2018, 11, 3)\n mult = 1.0\n instances = []\n \n def __init__(self,\n stock: 'str',\n event_input: 'float',\n idio_mult = 1.0):\n super().__init__(stock = stock,\n event_input = event_input,\n timing_descriptor = self.timing,\n idio_mult = idio_mult)\n \n logger.info(\"{} Presidential Election Event Instantiated Successfully\".format(self.stock))\n\nclass Earnings(Event):\n name = 'Earnings'\n abbrev_name = 'Earns.'\n timing = None\n mult = 1.0\n instances = []\n \n def __init__(self,\n stock: 'str',\n event_input: 'float',\n timing_descriptor,\n event_name = name,\n idio_mult = 1.0):\n super().__init__(stock = stock,\n event_input = event_input,\n timing_descriptor = timing_descriptor,\n event_name = event_name,\n idio_mult = idio_mult,\n )\n \n logger.info(\"{} {} Earnings Event Instantiated Successfully\".format(self.stock, self.quarter))\n \n def __repr__(self):\n return \"{} ({})\".format(self.abbrev_name, self.quarter)\n #return \"{} ({})\".format(self.abbrev_name, Timing(self.timing_descriptor).timing_descriptor_abbrev)\n #return \"{}-{} ({})\".format(self.abbrev_name, self.timing_descriptor, self.stock)\n \n @property\n def quarter(self):\n return self.event_name[0:2]\n \n @property\n def event_bid(self):\n return Earnings(self.stock,\n self.event_input*.925,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return Earnings(self.stock,\n self.event_input*1.075,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n\nclass ComplexEvent(Event):\n name = 'Complex_Event'\n abbrev_name = 'Complex_Evt'\n timing = None\n mult = 1.0\n instances = []\n \n def __init__(self,\n stock: 'str',\n event_input: 'float',\n timing_descriptor,\n event_name = None,\n idio_mult = 1.0):\n super().__init__(stock = stock,\n event_input = event_input,\n timing_descriptor = timing_descriptor,\n event_name = event_name,\n idio_mult = idio_mult,\n )\n \n logger.info(\"{} {} Complex Event Instantiated Successfully\".format(self.stock, self.timing_descriptor))\n @property\n def event_bid(self):\n return ComplexEvent(self.stock,\n self.event_input*.925,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n \n @property\n def event_ask(self):\n return ComplexEvent(self.stock,\n self.event_input*1.075,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n\n \n def event_prob_success(self, new_prob_success):\n new_distribution = Distribution_MultiIndex(self.event_input_distribution_df)\n new_distribution.set_prob_success(new_prob_success)\n new_event = ComplexEvent(self.stock,\n new_distribution,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n print(new_event.event_input_distribution_df.to_string())\n return new_event\n \n @property\n def event_high_prob_success(self):\n return self.event_prob_success(.95)\n\n @property\n def event_low_prob_success(self):\n return self.event_prob_success(.05)\n \n @property\n def event_max_optionality(self):\n new_distribution = Distribution_MultiIndex(self.event_input_distribution_df)\n \n most_positive_state = new_distribution.positive_scenario_states[0][1]\n new_distribution.set_positive_scenario_substate_prob(most_positive_state, 1.0)\n \n most_negative_state = new_distribution.negative_scenario_states[-1][1]\n new_distribution.set_negative_scenario_substate_prob(most_negative_state, 1.0)\n\n new_distribution.set_prob_success(.5)\n\n new_event = ComplexEvent(self.stock,\n new_distribution,\n self.timing_descriptor,\n self.event_name,\n self.idio_mult)\n print(new_event.event_input_distribution_df.to_string())\n return new_event\n return self.event_prob_success(.05)\n\nclass TakeoutEvent(GeneralEvent):\n name = 'Takeout'\n abbrev_name = 'T.O.'\n timing = None\n mult = 1.0\n instances = []\n \n takeout_buckets = pd.read_csv('TakeoutBuckets.csv')\n takeout_buckets.set_index('Rank', inplace=True)\n\n base_takeout_premium = .35\n base_mcap = 8750\n mcap_sensitivity = .3\n \"\"\"\n def __init__(self,\n stock: 'str',\n takeout_bucket: 'int',\n event_input: 'float or distribution object' = None,\n timing_descriptor = None,\n event_name = name,\n idio_mult = 1.0):\n super().__init__()\n \"\"\" \n def __init__(self, stock: 'str', takeout_bucket: 'int'):\n super().__init__()\n self.stock = stock\n self.takeout_bucket = takeout_bucket\n logger.info(\"{} Takeout Event Instantiated Successfully.\".format(self.stock))\n\n def __str__(self):\n return \"{}-{} ({})\".format(self.abbrev_name, self.takeout_bucket, self.stock)\n \n def __repr__(self):\n return \"{} Tier {} ({})\".format(self.abbrev_name, self.takeout_bucket, self.stock)\n\n @property\n def takeout_prob(self):\n return self.takeout_buckets.loc[self.takeout_bucket, 'Prob']\n \n @property\n def mcap(self):\n try:\n return InformationTable.loc[self.stock, 'Market Cap'] \n except Exception:\n logger.error(\"{} did not register a Market Cap. Check error source.\".format(self.stock))\n return self.base_mcap\n\n @property\n def takeout_premium_adjustment(self):\n return min(((1 / (self.mcap/self.base_mcap)) - 1)*self.mcap_sensitivity, 1.5)\n\n @property\n def takeout_premium(self):\n return self.base_takeout_premium * (1 + self.takeout_premium_adjustment)\n\n \n def get_distribution(self, expiry: 'dt.date', *args, **kwargs):\n time_to_expiry = get_time_to_expiry(expiry)\n prob_takeout_by_expiry = time_to_expiry * self.takeout_prob\n prob_no_takeout_by_expiry = 1 - prob_takeout_by_expiry\n\n relative_price_takeout = (1 + self.takeout_premium)\n relative_price_no_takeout = 1-(prob_takeout_by_expiry*self.takeout_premium) / (prob_no_takeout_by_expiry)\n \n distribution_info = {'States': ['Takeout', 'No Takeout'],\n 'Prob': [prob_takeout_by_expiry, prob_no_takeout_by_expiry],\n 'Relative_Price': [relative_price_takeout, relative_price_no_takeout],\n 'Pct_Move': [self.takeout_premium, relative_price_no_takeout-1]}\n \n distribution_df = pd.DataFrame(distribution_info).set_index('States').loc[:, ['Prob', 'Pct_Move', 'Relative_Price']]\n return Distribution(distribution_df)\n \n @property\n def event_bid(self):\n return TakeoutEvent(self.stock, min(self.takeout_bucket + 2, 7))\n #return TakeoutEvent(self.stock, 7)\n \n @property\n def event_ask(self):\n return TakeoutEvent(self.stock, max(self.takeout_bucket - 1, 1))\n","sub_path":"Old_Versions/Event_Module_oldR/Event_Module_4.py","file_name":"Event_Module_4.py","file_ext":"py","file_size_in_byte":14455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"529334388","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 19 14:04:54 2021\n\n@author: trduong\n\"\"\"\n\nimport torch \nimport pyro \n\ndef weather():\n cloudy = torch.distributions.Bernoulli(0.3).sample()\n cloudy = 'cloudy' if cloudy.item() == 1 else 'sunny'\n mean_temp = {'cloudy': 55.0, 'sunny': 75.0}[cloudy]\n scale_temp = {'cloudy': 10.0, 'sunny': 15.0}[cloudy]\n temp = torch.distributions.Normal(mean_temp, scale_temp).rsample()\n return cloudy, temp.item()\n\ndef ice_cream_sales():\n cloudy, temp = weather()\n expected_sales = 200. if cloudy == 'sunny' and temp > 80.0 else 50.\n ice_cream = pyro.sample('ice_cream', pyro.distributions.Normal(expected_sales, 10.0))\n return ice_cream\n\n\nif __name__ == \"__main__\":\n for _ in range(3):\n print(weather())","sub_path":"my-implementation/intro_pyro.py","file_name":"intro_pyro.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"223090375","text":"\"\"\"\nresolve.py: a recursive resolver built using dnspython\n\"\"\"\n\nimport argparse\n\nimport dns.message\nimport dns.name\nimport dns.query\nimport dns.rdata\nimport dns.rdataclass\nimport dns.rdatatype\n\nFORMATS = ((\"CNAME\", \"{alias} is an alias for {name}\"),\n (\"A\", \"{name} has address {address}\"),\n (\"AAAA\", \"{name} has IPv6 address {address}\"),\n (\"MX\", \"{name} mail is handled by {preference} {exchange}\"))\n\n# current as of 19 March 2018\nROOT_SERVERS = (\"198.41.0.4\",\n \"199.9.14.201\",\n \"192.33.4.12\",\n \"199.7.91.13\",\n \"192.203.230.10\",\n \"192.5.5.241\",\n \"192.112.36.4\",\n \"198.97.190.53\",\n \"192.36.148.17\",\n \"192.58.128.30\",\n \"193.0.14.129\",\n \"199.7.83.42\",\n \"202.12.27.33\")\n\nQUERIED_SERVERS_STACK = {} \n\ndef collect_results(name: str) -> dict:\n \"\"\"\"\n This function parses final answers into the proper data structure that\n print_results requires. The main work is done within the `lookup` function.\n \"\"\"\n full_response = {}\n target_name = dns.name.from_text(name)\n # lookup CNAME\n response = lookup(target_name, dns.rdatatype.CNAME)\n cnames = []\n for answers in response.answer:\n for answer in answers:\n cnames.append({\"name\": answer, \"alias\": name})\n # lookup A\n response = lookup(target_name, dns.rdatatype.A)\n arecords = []\n for answers in response.answer:\n a_name = answers.name\n for answer in answers:\n if answer.rdtype == 1: # A record\n arecords.append({\"name\": a_name, \"address\": str(answer)})\n # lookup AAAA\n response = lookup(target_name, dns.rdatatype.AAAA)\n aaaarecords = []\n for answers in response.answer:\n aaaa_name = answers.name\n for answer in answers:\n if answer.rdtype == 28: # AAAA record\n aaaarecords.append({\"name\": aaaa_name, \"address\": str(answer)})\n # lookup MX\n response = lookup(target_name, dns.rdatatype.MX)\n mxrecords = []\n for answers in response.answer:\n mx_name = answers.name\n for answer in answers:\n if answer.rdtype == 15: # MX record\n mxrecords.append({\"name\": mx_name,\n \"preference\": answer.preference,\n \"exchange\": str(answer.exchange)})\n\n full_response[\"CNAME\"] = cnames\n full_response[\"A\"] = arecords\n full_response[\"AAAA\"] = aaaarecords\n full_response[\"MX\"] = mxrecords\n\n return full_response\n\ndef lookup(target_name: dns.name.Name,\n qtype: dns.rdata.Rdata) -> dns.message.Message:\n \"\"\"\n This function uses a recursive resolver to find the relevant answer to the\n query.\n\n TODO: replace this implementation with one which asks the root servers\n and recurses to find the proper answer.\n \"\"\"\n outbound_query = dns.message.make_query(target_name, qtype)\n for addr in ROOT_SERVERS:\n try:\n response = dns.query.udp(outbound_query, addr, 3)\n except dns.exception.Timeout:\n continue\n except dns.query.BadResponse:\n continue\n except dns.query.UnexpectedSource:\n continue\n '''\n For every A record in received in the response, add it to the set\n of unique server\n '''\n name_servers = []#store all the unique name server to a query\n for each in response.additional:\n if each.rdtype == dns.rdatatype.A and each not in name_servers:\n name_servers.append(each)\n\n auth_servers = []\n for each in name_servers:\n try:\n _name_query = dns.message.make_query(target_name, qtype)\n response = dns.query.udp(_name_query, str(each.items[0]), 3)\n except dns.exception.Timeout:\n continue\n except dns.query.BadResponse:\n continue\n except dns.query.UnexpectedSource:\n continue\n if response.answer:\n return response\n if response.authority and not response.additional:\n continue\n for each in response.additional:\n if each.rdtype == dns.rdatatype.A:\n try:\n _authority_query = dns.message.make_query(target_name,\n qtype)\n response = dns.query.udp(_authority_query,\n str(each.items[0]), 3)\n except dns.exception.Timeout:\n continue\n except dns.query.BadResponse:\n continue\n except dns.query.UnexpectedSource:\n continue\n if response.answer:\n return response\n #QUERIED_SERVERS_STACK.update\n return response\n\ndef print_results(results: dict) -> None:\n \"\"\"\n take the results of a `lookup` and print them to the screen like the host\n program would.\n \"\"\"\n\n for rtype, fmt_str in FORMATS:\n for result in results.get(rtype, []):\n print(fmt_str.format(**result))\n\ndef main():\n \"\"\"\n if run from the command line, take args and call\n printresults(lookup(hostname))\n \"\"\"\n argument_parser = argparse.ArgumentParser()\n argument_parser.add_argument(\"name\", nargs=\"+\",\n help=\"DNS name(s) to look up\")\n argument_parser.add_argument(\"-v\", \"--verbose\",\n help=\"increase output verbosity\",\n action=\"store_true\")\n program_args = argument_parser.parse_args()\n fuckall = []\n for a_domain_name in program_args.name:\n if a_domain_name not in fuckall:\n print_results(collect_results(a_domain_name))\n fuckall.append(a_domain_name)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hw4/resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"373705246","text":"import numpy as np\nimport matplotlib.pyplot as plot\n\ndef coefs():\n return 4,3,1\n\ndef f(x):\n a, b, c = coefs()\n return a * x[0] + x[1] + 4 * np.sqrt(1 + b * x[0] ** 2 + c * x[1] ** 2)\n\ndef grad_f(x):\n a, b, c = coefs()\n return np.asarray([a + 4 * b * x[0] / np.sqrt(1 + b * x[0] ** 2 + c * x[1] ** 2),\n 1 + 4 * c * x[1] / np.sqrt(1 + b * x[0] ** 2 + c * x[1] ** 2)])\n\ndef norm(x):\n if x is None:\n return float('inf')\n return np.sqrt(x[0] ** 2 + x[1] ** 2)\n\ndef fib(n):\n numbers = [1, 1]\n for i in range(2, n):\n num = numbers[i - 2] + numbers[i - 1]\n numbers.append(num)\n return numbers\n\ndef fib_min(nums, x_k, grad_k):\n a = 0\n b = 1\n lam = a + nums[-3] / nums[-1] * (b - a)\n mu = a + nums[-2] / nums[-1] * (b - a)\n f_lam = f(x_k - lam * grad_k)\n f_mu = f(x_k - mu * grad_k)\n for i in range(1, len(nums)):\n if f_lam > f_mu:\n a = lam\n lam = mu\n mu = a + nums[-1 - i - 1] / nums[-1 - i] * (b - a)\n if i == len(nums) - 3:\n break\n f_lam = f_mu\n f_mu = f(x_k - mu * grad_k)\n else:\n b = mu\n mu = lam\n lam = a + nums[-1 - i - 2] / nums[-1 - i] * (b - a)\n if i == len(nums) - 3:\n break\n f_mu = f_lam\n f_lam = f(x_k - lam * grad_k)\n if f_lam >= f_mu:\n return (lam + b) / 2\n else:\n return (a + mu) / 2\n\nclass Solver:\n x: list\n iters = 0\n fib_iter_num = 20\n\n def __init__(self):\n self.x = []\n\n def get_x_seq(self):\n return self.x.copy()\n\n def get_iter_num(self):\n return self.iters\n\n def draw_contoures(self):\n fig, axis = plot.subplots()\n x = np.ndarray((1,len(self.x)))\n y = np.ndarray((1,len(self.x)))\n for i in range(len(self.x)):\n x[0, i] = self.x[i][0]\n y[0, i] = self.x[i][1]\n x_mesh_min = np.min(x)\n x_mesh_max = np.max(x)\n x_mesh_delta = (x_mesh_max - x_mesh_min) / 10\n x_mesh_min -= x_mesh_delta\n x_mesh_max += x_mesh_delta\n y_mesh_min = np.min(y)\n y_mesh_max = np.max(y)\n y_mesh_delta = (y_mesh_max - y_mesh_min) / 10\n y_mesh_min -= y_mesh_delta\n y_mesh_max += y_mesh_delta\n mesh_dest = max(x_mesh_max - x_mesh_min, y_mesh_max - y_mesh_min)\n x_mesh_max = x_mesh_min + mesh_dest\n y_mesh_max = y_mesh_min + mesh_dest\n x_mesh, y_mesh = np.mgrid[x_mesh_min:x_mesh_max:100j, y_mesh_min:y_mesh_max:100j]\n z = np.ndarray(x_mesh.shape)\n for i in range(x_mesh.shape[0]):\n for j in range(x_mesh.shape[1]):\n z[i,j] = f((x_mesh[i,j], y_mesh[i,j]))\n cs = axis.contour(x_mesh, y_mesh, z, levels=15)\n axis.plot(x.tolist()[0], y.tolist()[0], 'bX--')\n axis.clabel(cs, colors=\"black\")\n fig.set_figwidth(8)\n fig.set_figheight(8)\n return fig, axis\n\n\nclass FastestDesc(Solver):\n def __init__(self):\n super(FastestDesc, self).__init__()\n\n def get_solution(self, x_0, eps):\n self.x = [np.asarray(x_0)]\n self.iters = 0\n fib_nums = fib(self.fib_iter_num)\n grad = None\n while norm(grad) >= eps:\n grad = grad_f(self.x[-1])\n alpha = fib_min(fib_nums, self.x[-1], grad)\n self.x.append(self.x[-1] - alpha * grad)\n self.iters += 1\n print(\"x1 = \", self.x[-1][0], \"x2 = \", self.x[-1][1])\n print(\"step =\", alpha)\n return self.x[-1]\n\nclass DFP(Solver):\n def __init__(self):\n super().__init__()\n\n def refresh_matrix(self, A):\n dx = self.x[-1] - self.x[-2]\n dw = grad_f(self.x[-2]) - grad_f(self.x[-1])\n return A - np.outer(dx, dx) / np.dot(dw, dx) - A.dot(np.outer(dw, dw)).dot(A.transpose()) / (np.dot(dw, A.dot(dw)))\n\n def get_solution(self, x_0, eps):\n self.x = [np.asarray(x_0)]\n self.iters = 0\n fib_nums = fib(self.fib_iter_num)\n grad = None\n A = np.eye(2)\n while norm(grad) >= eps:\n grad = grad_f(self.x[-1])\n p = A.dot(grad)\n alpha = fib_min(fib_nums, self.x[-1], p)\n self.x.append(self.x[-1] - alpha * p)\n self.iters += 1\n if self.iters % 2 == 0:\n A = self.refresh_matrix(A)\n print(\"x1 = \", self.x[-1][0],\"x2 = \", self.x[-1][1] )\n print(\"step =\", alpha)\n return self.x[-1]\n","sub_path":"LAB4/gradient/DFP.py","file_name":"DFP.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"371067067","text":"#last updated by Andre on 9/02/2015\nfrom Node import Node\n\nclass Signal:\n def __init__(self, experiment, link, value):\n self.experiment = experiment\n self.turnSent = experiment.turnCount\n self.link = link\n self.value = value\n link.end.receivedSignals.append(self)\n link.start.sentSignals.append(self)\n \n \n","sub_path":"Signal.py","file_name":"Signal.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"577704545","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def is_sys_tree(self, root):\n def check(p, q):\n if not p and not q:\n return True\n if not p or not q:\n return False\n if p.val != q.val:\n return False\n return check(p.left, q.right) and check(p.right, q.left)\n return check(root, root)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nprint(\"--------------------ansert----------------------思路1\")\n\n\n# class Solution(object):\n# def isSymmetric(self, root):\n# \"\"\"\n# :type root: TreeNode\n# :rtype: bool\n# \"\"\"\n#\n# def check(node1, node2):\n# if not node1 and not node2:\n# return True\n# elif not node1 or not node2:\n# return False\n#\n# if node1.val != node2.val:\n# return False\n# return check(node1.left, node2.right) and check(node1.right, node2.left)\n#\n# return check(root, root)\n\n\n","sub_path":"sample/100_Same_Tree.py","file_name":"100_Same_Tree.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"268572325","text":"import warnings\nimport copy\nimport json\nimport logging\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom numbers import Number\nimport os\nfrom pathlib import Path\nimport platform\nimport re\nimport shutil\nimport time\nfrom typing import Any, Dict, Optional, Sequence, Union, Callable, List, Tuple\nimport uuid\n\nimport ray\nfrom ray.air import CheckpointConfig\nfrom ray.air._internal.uri_utils import URI\nfrom ray.air._internal.checkpoint_manager import _TrackedCheckpoint, CheckpointStorage\nfrom ray.air.constants import (\n EXPR_ERROR_PICKLE_FILE,\n EXPR_ERROR_FILE,\n TRAINING_ITERATION,\n)\n\nimport ray.cloudpickle as cloudpickle\nfrom ray.exceptions import RayActorError, RayTaskError\nfrom ray.train import Checkpoint\nfrom ray.train._internal.checkpoint_manager import (\n _TrainingResult,\n _CheckpointManager as _NewCheckpointManager,\n)\nfrom ray.train._internal.storage import _use_storage_context, StorageContext\nfrom ray.tune import TuneError\nfrom ray.tune.error import _TuneRestoreError\nfrom ray.tune.execution.checkpoint_manager import _CheckpointManager\nfrom ray.tune.logger import NoopLogger\n\n# NOTE(rkn): We import ray.tune.registry here instead of importing the names we\n# need because there are cyclic imports that may cause specific names to not\n# have been defined yet. See https://github.com/ray-project/ray/issues/1716.\nfrom ray.tune.registry import get_trainable_cls, validate_trainable\nfrom ray.tune.result import (\n DONE,\n NODE_IP,\n PID,\n TRIAL_ID,\n DEBUG_METRICS,\n TRIAL_INFO,\n STDOUT_FILE,\n STDERR_FILE,\n DEFAULT_EXPERIMENT_NAME,\n _get_defaults_results_dir,\n)\nfrom ray.train import SyncConfig\nfrom ray.tune.execution.placement_groups import (\n PlacementGroupFactory,\n resource_dict_to_pg_factory,\n)\nfrom ray.tune.trainable.metadata import _TrainingRunMetadata\nfrom ray.tune.utils.serialization import TuneFunctionDecoder, TuneFunctionEncoder\nfrom ray.tune.trainable.util import TrainableUtil\nfrom ray.tune.utils import date_str, flatten_dict\nfrom ray.tune.utils.util import _split_remote_local_path\nfrom ray.util.annotations import DeveloperAPI, Deprecated\nfrom ray.util.debug import log_once\nfrom ray._private.utils import binary_to_hex, hex_to_binary\n\n\nDEBUG_PRINT_INTERVAL = 5\n_DEFAULT_WIN_MAX_PATH_LENGTH = 260\nTRIAL_STATE_FILENAME = \"trial_metadata.json\"\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass _Location:\n \"\"\"Describes the location at which Trial is placed to run.\"\"\"\n\n def __init__(self, hostname=None, pid=None):\n self.hostname = hostname\n self.pid = pid\n\n def __str__(self):\n if not self.pid:\n return \"\"\n elif self.hostname == platform.node():\n return \"pid={}\".format(self.pid)\n else:\n return \"{}:{}\".format(self.hostname, self.pid)\n\n\n@DeveloperAPI\nclass ExportFormat:\n \"\"\"Describes the format to import/export the trial Trainable.\n\n This may correspond to different file formats based on the\n Trainable implementation.\n \"\"\"\n\n CHECKPOINT = \"checkpoint\"\n MODEL = \"model\"\n ONNX = \"onnx\"\n H5 = \"h5\"\n\n @staticmethod\n def validate(formats):\n \"\"\"Validates formats.\n\n Raises:\n ValueError if the format is unknown.\n \"\"\"\n for i in range(len(formats)):\n formats[i] = formats[i].strip().lower()\n if formats[i] not in [\n ExportFormat.CHECKPOINT,\n ExportFormat.MODEL,\n ExportFormat.ONNX,\n ExportFormat.H5,\n ]:\n raise TuneError(\"Unsupported import/export format: \" + formats[i])\n\n\nclass _CheckpointDeleter:\n \"\"\"Checkpoint deleter callback for a runner.\"\"\"\n\n def __init__(self, trial_id, ray_actor):\n self.trial_id = trial_id\n self.ray_actor = ray_actor\n\n def __call__(self, checkpoint: _TrackedCheckpoint):\n \"\"\"Requests checkpoint deletion asynchronously.\n\n Args:\n checkpoint: Checkpoint to delete.\n \"\"\"\n if not self.ray_actor:\n return\n\n if (\n checkpoint.storage_mode == CheckpointStorage.PERSISTENT\n and checkpoint.dir_or_data\n ):\n checkpoint_path = checkpoint.dir_or_data\n\n logger.debug(\n \"Trial %s: Deleting checkpoint %s\", self.trial_id, checkpoint_path\n )\n\n # TODO(ujvl): Batch remote deletes.\n # We first delete the remote checkpoint. If it is on the same\n # node as the driver, it will also remove the local copy.\n ray.get(self.ray_actor.delete_checkpoint.remote(checkpoint_path))\n\n # Delete local copy, if any exists.\n if os.path.exists(checkpoint_path):\n try:\n checkpoint_dir = TrainableUtil.find_checkpoint_dir(checkpoint_path)\n shutil.rmtree(checkpoint_dir)\n except FileNotFoundError:\n logger.debug(\"Local checkpoint dir not found during deletion.\")\n\n\nclass _TrialInfo:\n \"\"\"Serializable struct for holding information for a Trial.\n\n Attributes:\n trial_name: String name of the current trial.\n trial_id: trial_id of the trial\n trial_resources: resources used by trial.\n \"\"\"\n\n def __init__(self, trial: \"Trial\"):\n self._trial_name = str(trial)\n self._trial_id = trial.trial_id\n self._trial_resources = trial.placement_group_factory\n self._experiment_name = trial.experiment_dir_name\n\n @property\n def experiment_name(self):\n return self._experiment_name\n\n @property\n def trial_name(self):\n return self._trial_name\n\n @property\n def trial_id(self):\n return self._trial_id\n\n @property\n def trial_resources(self) -> PlacementGroupFactory:\n return self._trial_resources\n\n @trial_resources.setter\n def trial_resources(self, new_resources: PlacementGroupFactory):\n self._trial_resources = new_resources\n\n\nclass _TemporaryTrialState:\n \"\"\"Temporary trial state.\n\n Values saved here should not be restored on resume.\n \"\"\"\n\n def __init__(self):\n self.location = _Location()\n\n self.ray_actor = None\n\n self.saving_to = None\n self.restoring_from = None\n\n self.num_restore_failures = 0\n\n def __getstate__(self):\n return {}\n\n\ndef _get_max_path_length() -> int:\n if hasattr(os, \"pathconf\"):\n return os.pathconf(\"/\", \"PC_PATH_MAX\")\n # Windows\n return _DEFAULT_WIN_MAX_PATH_LENGTH\n\n\ndef _create_unique_logdir_name(root: str, relative_logdir: str) -> str:\n candidate = Path(root).expanduser().joinpath(relative_logdir)\n if candidate.exists():\n relative_logdir_old = relative_logdir\n relative_logdir += \"_\" + uuid.uuid4().hex[:4]\n logger.info(\n f\"Creating a new dirname {relative_logdir} because \"\n f\"trial dirname '{relative_logdir_old}' already exists.\"\n )\n return relative_logdir\n\n\ndef _noop_logger_creator(\n config: Dict[str, Any], logdir: str, should_chdir: bool = True\n):\n # Upon remote process setup, record the actor's original working dir before\n # changing to the Tune logdir\n os.environ.setdefault(\"TUNE_ORIG_WORKING_DIR\", os.getcwd())\n\n os.makedirs(logdir, exist_ok=True)\n if should_chdir:\n # Set the working dir to the trial directory in the remote process,\n # for user file writes\n if not ray._private.worker._mode() == ray._private.worker.LOCAL_MODE:\n os.chdir(logdir)\n return NoopLogger(config, logdir)\n\n\ndef _get_trainable_kwargs(\n trial: \"Trial\",\n should_chdir: bool = False,\n) -> Dict[str, Any]:\n trial.init_local_path()\n\n logger_creator = partial(\n _noop_logger_creator,\n logdir=trial.local_path,\n should_chdir=should_chdir,\n )\n\n trial_config = copy.deepcopy(trial.config)\n trial_config[TRIAL_INFO] = _TrialInfo(trial)\n stdout_file, stderr_file = trial.log_to_file\n trial_config[STDOUT_FILE] = stdout_file\n trial_config[STDERR_FILE] = stderr_file\n\n kwargs = {\n \"config\": trial_config,\n \"logger_creator\": logger_creator,\n }\n\n if _use_storage_context():\n assert trial.storage\n assert trial.storage.trial_dir_name\n kwargs[\"storage\"] = trial.storage\n\n if trial.uses_cloud_checkpointing:\n # We keep these kwargs separate for backwards compatibility\n # with trainables that don't provide these keyword arguments\n kwargs[\"remote_checkpoint_dir\"] = trial.remote_path\n kwargs[\"sync_config\"] = trial.legacy_sync_config\n\n return kwargs\n\n\n@contextmanager\ndef _change_working_directory(trial):\n \"\"\"Context manager changing working directory to trial logdir.\n Used in local mode.\n\n For non-local mode it is no-op.\n \"\"\"\n if ray._private.worker._mode() == ray._private.worker.LOCAL_MODE:\n old_dir = os.getcwd()\n try:\n os.chdir(trial.local_path)\n yield\n finally:\n os.chdir(old_dir)\n else:\n yield\n\n\n@DeveloperAPI\nclass Trial:\n \"\"\"A trial object holds the state for one model training run.\n\n Trials are themselves managed by the TrialRunner class, which implements\n the event loop for submitting trial runs to a Ray cluster.\n\n Trials start in the PENDING state, and transition to RUNNING once started.\n On error, it transitions to ERROR, otherwise TERMINATED on success.\n\n There are resources allocated to each trial. These should be specified\n using ``PlacementGroupFactory``.\n\n Attributes:\n trainable_name: Name of the trainable object to be executed.\n config: Provided configuration dictionary with evaluated params.\n trial_id: Unique identifier for the trial.\n path: Path where results for this trial are stored. Can be on\n the local node or on cloud storage.\n local_path: Path on the local disk where results are stored.\n remote_path: Path on cloud storage where results are stored,\n or None if not set.\n relative_logdir: Directory of the trial relative to its\n experiment directory.\n evaluated_params: Evaluated parameters by search algorithm,\n experiment_tag: Identifying trial name to show in the console\n status: One of PENDING, RUNNING, PAUSED, TERMINATED, ERROR/\n error_file: Path to the errors that this trial has raised.\n\n \"\"\"\n\n _nonjson_fields = [\n \"results\",\n \"extra_arg\",\n \"placement_group_factory\",\n \"_resources\",\n \"_default_placement_group_factory\",\n ]\n\n PENDING = \"PENDING\"\n RUNNING = \"RUNNING\"\n PAUSED = \"PAUSED\"\n TERMINATED = \"TERMINATED\"\n ERROR = \"ERROR\"\n\n def __init__(\n self,\n trainable_name: str,\n *,\n config: Optional[Dict] = None,\n trial_id: Optional[str] = None,\n storage: Optional[StorageContext] = None,\n experiment_path: Optional[str] = None,\n experiment_dir_name: Optional[str] = None,\n evaluated_params: Optional[Dict] = None,\n experiment_tag: str = \"\",\n placement_group_factory: Optional[PlacementGroupFactory] = None,\n stopping_criterion: Optional[Dict[str, float]] = None,\n sync_config: Optional[SyncConfig] = None,\n checkpoint_config: Optional[CheckpointConfig] = None,\n export_formats: Optional[List[str]] = None,\n restore_path: Optional[str] = None,\n trial_name_creator: Optional[Callable[[\"Trial\"], str]] = None,\n trial_dirname_creator: Optional[Callable[[\"Trial\"], str]] = None,\n log_to_file: Union[Optional[str], Tuple[Optional[str], Optional[str]]] = None,\n max_failures: int = 0,\n stub: bool = False,\n _setup_default_resource: bool = True,\n # Deprecated\n local_dir: Optional[str] = None,\n ):\n \"\"\"Initialize a new trial.\n\n The args here take the same meaning as the command line flags defined\n in ray.tune.experiment.config_parser.\n\n Args:\n _setup_default_resource: Whether to set up default resources.\n When initializing trials from checkpoints, this field is set to false,\n so that setting up default resources can be delayed till after\n ``trial.config`` is loaded from checkpoints.\n \"\"\"\n # If this is set, trainables are not validated or looked up.\n # This can be used e.g. to initialize Trial objects from checkpoints\n # without loading the trainable first.\n self.stub = stub\n\n if not self.stub:\n validate_trainable(trainable_name)\n # Trial config\n self.trainable_name = trainable_name\n self.trial_id = Trial.generate_id() if trial_id is None else trial_id\n\n self.temporary_state = _TemporaryTrialState()\n self.run_metadata = _TrainingRunMetadata()\n\n # Create a copy, since `init_local_path` updates the context with the\n # generated trial dirname.\n self.storage = copy.copy(storage)\n\n if _use_storage_context():\n self._legacy_orig_experiment_path = None\n self._legacy_orig_experiment_dir_name = None\n self._legacy_local_experiment_path = None\n self._legacy_remote_experiment_path = None\n self._legacy_experiment_dir_name = None\n self.legacy_sync_config = None\n else:\n # Set to pass through on `Trial.reset()`\n self._legacy_orig_experiment_path = experiment_path\n self._legacy_orig_experiment_dir_name = experiment_dir_name\n\n self._legacy_experiment_dir_name = experiment_dir_name\n\n # Sync config\n self.legacy_sync_config = sync_config or SyncConfig()\n\n local_experiment_path, remote_experiment_path = _split_remote_local_path(\n experiment_path, None\n )\n\n # Backwards compatibility for `local_dir`\n if local_dir:\n if local_experiment_path:\n raise ValueError(\n \"Only one of `local_dir` or `experiment_path` \"\n \"can be passed to `Trial()`.\"\n )\n local_experiment_path = local_dir\n\n # Derive experiment dir name from local path\n if not experiment_dir_name and local_experiment_path:\n # Maybe derive experiment dir name from local storage dir\n experiment_dir_name = Path(local_experiment_path).name\n elif not experiment_dir_name:\n experiment_dir_name = DEFAULT_EXPERIMENT_NAME\n\n # Set default experiment dir name\n if not local_experiment_path:\n local_experiment_path = str(\n Path(_get_defaults_results_dir()) / experiment_dir_name\n )\n os.makedirs(local_experiment_path, exist_ok=True)\n\n # Set remote experiment path if upload_dir is set\n if self.legacy_sync_config.upload_dir:\n if remote_experiment_path:\n if not remote_experiment_path.startswith(\n self.legacy_sync_config.upload_dir\n ):\n raise ValueError(\n f\"Both a `SyncConfig.upload_dir` and an `experiment_path` \"\n f\"pointing to remote storage were passed, but they do not \"\n f\"point to the same location. Got: \"\n f\"`experiment_path={experiment_path}` and \"\n \"`SyncConfig.upload_dir=\"\n f\"{self.legacy_sync_config.upload_dir}`. \"\n )\n warnings.warn(\n \"If `experiment_path` points to a remote storage location, \"\n \"do not set `SyncConfig.upload_dir`. \",\n DeprecationWarning,\n )\n else:\n remote_experiment_path = str(\n URI(self.legacy_sync_config.upload_dir) / experiment_dir_name\n )\n\n # Finally, set properties\n self._legacy_local_experiment_path = local_experiment_path\n self._legacy_remote_experiment_path = remote_experiment_path\n\n self.config = config or {}\n # Save a copy of the original unresolved config so that we can swap\n # out and update any reference config values after restoration.\n self.__unresolved_config = self.config\n\n # Parameters that Tune varies across searches.\n self.evaluated_params = evaluated_params or {}\n self.experiment_tag = experiment_tag\n self.stopping_criterion = stopping_criterion or {}\n\n self._setup_default_resource = _setup_default_resource\n\n if placement_group_factory and not isinstance(\n placement_group_factory, PlacementGroupFactory\n ):\n placement_group_factory = resource_dict_to_pg_factory(\n placement_group_factory\n )\n\n self._default_placement_group_factory = placement_group_factory\n # Will be created in create_placement_group_factory().\n self.placement_group_factory = None\n\n self.log_to_file = log_to_file\n # Make sure `stdout_file, stderr_file = Trial.log_to_file` works\n if (\n not self.log_to_file\n or not isinstance(self.log_to_file, Sequence)\n or not len(self.log_to_file) == 2\n ):\n self.log_to_file = (None, None)\n\n self.max_failures = max_failures\n\n # Local trial state that is updated during the run\n self._default_result_or_future: Union[ray.ObjectRef, dict, None] = None\n\n self.export_formats = export_formats\n self.status = Trial.PENDING\n self.relative_logdir = None\n\n self.trial_name_creator = trial_name_creator\n self.trial_dirname_creator = trial_dirname_creator\n self.custom_trial_name = None\n self.custom_dirname = None\n\n # Checkpoint config\n checkpoint_config = checkpoint_config or CheckpointConfig()\n if not _use_storage_context():\n # TODO(justinvyu): Why is this needed?\n checkpoint_config.checkpoint_score_attribute = (\n checkpoint_config.checkpoint_score_attribute or TRAINING_ITERATION\n )\n\n if _use_storage_context():\n self.run_metadata.checkpoint_manager = _NewCheckpointManager(\n checkpoint_config=checkpoint_config\n )\n else:\n self.run_metadata.checkpoint_manager = _CheckpointManager(\n checkpoint_config=checkpoint_config,\n delete_fn=_CheckpointDeleter(str(self), self.temporary_state.ray_actor),\n )\n\n # Restoration fields\n self.restore_path = restore_path\n self._restore_checkpoint_result: Optional[_TrainingResult] = None\n if restore_path:\n # tune.run(restore) passes in a path without metrics.\n self._restore_checkpoint_result = _TrainingResult(\n checkpoint=Checkpoint.from_directory(restore_path), metrics={}\n )\n\n if trial_name_creator:\n self.custom_trial_name = trial_name_creator(self)\n\n if trial_dirname_creator:\n self.custom_dirname = trial_dirname_creator(self)\n if os.path.sep in self.custom_dirname:\n raise ValueError(\n f\"Trial dirname must not contain '/'. Got {self.custom_dirname}\"\n )\n\n self._state_json = None\n\n def create_placement_group_factory(self):\n \"\"\"Compute placement group factory if needed.\n\n Note: this must be called after all the placeholders in\n self.config are resolved.\n \"\"\"\n trainable_cls = self.get_trainable_cls()\n if not trainable_cls or not self._setup_default_resource:\n # Create placement group factory using default resources.\n self.placement_group_factory = (\n self._default_placement_group_factory or resource_dict_to_pg_factory()\n )\n return\n\n default_resources = trainable_cls.default_resource_request(self.config)\n\n # If Trainable returns resources, do not allow manual override via\n # `resources_per_trial` by the user.\n if default_resources and self._default_placement_group_factory:\n raise TuneError(\n \"Resources for {} have been automatically set to {} \"\n \"by its `default_resource_request()` method. Please \"\n \"clear the `resources_per_trial` option.\".format(\n trainable_cls, default_resources\n )\n )\n\n if default_resources and not isinstance(\n default_resources, PlacementGroupFactory\n ):\n default_resources = resource_dict_to_pg_factory(default_resources)\n\n self.placement_group_factory = (\n # default_resource_request\n default_resources\n # resources_per_trial\n or self._default_placement_group_factory\n # cpu=1\n or resource_dict_to_pg_factory()\n )\n\n def _get_default_result_or_future(self) -> Optional[dict]:\n \"\"\"Calls ray.get on self._default_result_or_future and assigns back.\n\n Returns None in case of exceptions.\n Will also set the trial location if runner is set.\n \"\"\"\n if self._default_result_or_future and isinstance(\n self._default_result_or_future, ray.ObjectRef\n ):\n try:\n self._default_result_or_future = ray.get(self._default_result_or_future)\n except RayActorError: # error during initialization\n self._default_result_or_future = None\n if self._default_result_or_future and self.temporary_state.ray_actor:\n self.set_location(\n _Location(\n self._default_result_or_future.get(NODE_IP),\n self._default_result_or_future.get(PID),\n )\n )\n return self._default_result_or_future\n\n def resolve_config_placeholders(self, placeholder_resolvers: Dict[Tuple, Any]):\n from ray.tune.impl.placeholder import resolve_placeholders\n\n # Make a copy of the unresolved config before resolve it.\n self.config = copy.deepcopy(self.__unresolved_config)\n resolve_placeholders(self.config, placeholder_resolvers)\n\n @property\n def last_result(self) -> dict:\n # The logic in here is as follows:\n # 1. If the trial has reported at least once, last_result would have\n # been set and therefore would not be empty. We can just return it.\n # 2. If the trial has not reported at least once but we have the\n # future for the default results dict, (obtained through\n # Trainable.get_auto_filled_metrics), we get that future\n # and return it.\n # 3. In the worst case where we have nothing, we just set the\n # trial_id and return that.\n result = self.run_metadata.last_result\n if not {k for k in result if k != TRIAL_ID}:\n self._get_default_result_or_future()\n result = self._default_result_or_future or result\n result.setdefault(TRIAL_ID, self.trial_id)\n return result\n\n @property\n def metric_analysis(self):\n return self.run_metadata.metric_analysis\n\n @property\n def metric_n_steps(self):\n return self.run_metadata.metric_n_steps\n\n def get_ray_actor_ip(self) -> Optional[str]:\n if self.temporary_state.location.hostname:\n return self.temporary_state.location.hostname\n\n if not self.temporary_state.ray_actor:\n return None\n\n hostname, pid = ray.get(\n self.temporary_state.ray_actor.get_current_ip_pid.remote()\n )\n self.temporary_state.location = _Location(hostname, pid)\n return self.temporary_state.location.hostname\n\n @property\n @Deprecated(\"Replaced by `local_experiment_path`\")\n def local_dir(self):\n return self.local_experiment_path\n\n @property\n def experiment_dir_name(self):\n if _use_storage_context():\n return self.storage.experiment_dir_name\n\n return self._legacy_experiment_dir_name\n\n @experiment_dir_name.setter\n def experiment_dir_name(self, name: str):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.experiment_dir_name instead.\")\n\n self._legacy_experiment_dir_name = name\n\n @property\n def remote_experiment_path(self) -> str:\n if _use_storage_context():\n return self.storage.experiment_fs_path\n\n return str(self._legacy_remote_experiment_path)\n\n @remote_experiment_path.setter\n def remote_experiment_path(self, remote_path: str):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.experiment_dir_name instead.\")\n\n self._legacy_remote_experiment_path = remote_path\n\n @property\n def local_experiment_path(self) -> str:\n if _use_storage_context():\n return self.storage.experiment_local_path\n\n return str(self._legacy_local_experiment_path)\n\n @local_experiment_path.setter\n def local_experiment_path(self, local_path: str):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.experiment_dir_name instead.\")\n\n relative_checkpoint_dirs = []\n if self.local_path:\n # Save the relative paths of persistent trial checkpoints, which are saved\n # relative to the old `local_dir`/`logdir`\n for checkpoint in self.get_trial_checkpoints():\n checkpoint_dir = checkpoint.dir_or_data\n if not isinstance(checkpoint_dir, str):\n logger.warning(\n f\"No data found in checkpoint for trial {self} and metrics \"\n f\"{checkpoint.metrics} (type: {type(checkpoint_dir)}). \"\n f\"Skipping.\"\n )\n continue\n\n relative_checkpoint_dirs.append(\n os.path.relpath(checkpoint_dir, self.local_path)\n )\n\n # Update the underlying `_legacy_local_experiment_path`,\n # which also updates the trial `local_path`\n self._legacy_local_experiment_path = local_path\n\n if self.local_path:\n for checkpoint, relative_checkpoint_dir in zip(\n self.get_trial_checkpoints(), relative_checkpoint_dirs\n ):\n # Reconstruct the checkpoint dir using the (possibly updated)\n # trial logdir and the relative checkpoint directory.\n checkpoint.dir_or_data = os.path.join(\n self.local_path, relative_checkpoint_dir\n )\n\n @property\n @Deprecated(\"Replaced by `local_path`\")\n def logdir(self) -> Optional[str]:\n # Deprecate: Raise in 2.5, Remove in 2.6\n return self.local_path\n\n @property\n def local_path(self) -> Optional[str]:\n if _use_storage_context():\n return self.storage.trial_local_path\n\n if not self.local_experiment_path or not self.relative_logdir:\n return None\n return str(Path(self.local_experiment_path).joinpath(self.relative_logdir))\n\n @local_path.setter\n def local_path(self, logdir):\n if _use_storage_context():\n raise RuntimeError(\"Set storage.trial_dir_name instead.\")\n\n relative_logdir = Path(logdir).relative_to(self.local_experiment_path)\n if \"..\" in str(relative_logdir):\n raise ValueError(\n f\"The `local_path` points to a directory outside the trial's \"\n f\"`local_experiment_path` ({self.local_experiment_path}), \"\n f\"which is unsupported. Use a logdir within the \"\n f\"local directory instead. Got: {logdir}\"\n )\n if log_once(\"logdir_setter\"):\n logger.warning(\n \"Deprecated. In future versions only the relative logdir \"\n \"will be used and calling logdir will raise an error.\"\n )\n self.relative_logdir = relative_logdir\n\n @property\n @Deprecated(\"Replaced by `remote_path`\")\n def remote_checkpoint_dir(self) -> Optional[str]:\n # Deprecate: Raise in 2.5, Remove in 2.6\n return self.remote_path\n\n @property\n def remote_path(self) -> Optional[str]:\n # TODO(justinvyu): Remove remote_path. It's just path vs local_path now.\n if _use_storage_context():\n return self.path\n\n if not self._legacy_remote_experiment_path or not self.relative_logdir:\n return None\n uri = URI(self._legacy_remote_experiment_path)\n return str(uri / self.relative_logdir)\n\n @property\n def path(self) -> Optional[str]:\n if _use_storage_context():\n return self.storage.trial_fs_path\n\n return self.remote_path or self.local_path\n\n @property\n def has_reported_at_least_once(self) -> bool:\n return bool(self.run_metadata.last_result)\n\n @property\n def node_ip(self):\n return self.location.hostname\n\n @property\n def sync_on_checkpoint(self):\n if _use_storage_context():\n return self.storage.sync_config.sync_on_checkpoint\n\n return self.legacy_sync_config.sync_on_checkpoint\n\n @property\n def checkpoint_at_end(self):\n config = self.run_metadata.checkpoint_manager.checkpoint_config\n return config.checkpoint_at_end\n\n @property\n def checkpoint_freq(self):\n config = self.run_metadata.checkpoint_manager.checkpoint_config\n return config.checkpoint_frequency\n\n @property\n def latest_checkpoint_result(self) -> Optional[_TrainingResult]:\n # NOTE: Fallback to the checkpoint passed in from `tune.run(restore)`\n # if the trial hasn't saved any checkpoints itself yet.\n return (\n self.run_metadata.checkpoint_manager.latest_checkpoint_result\n or self._restore_checkpoint_result\n )\n\n @property\n def checkpoint(self) -> Optional[Checkpoint]:\n \"\"\"Returns the most recent checkpoint if one has been saved.\"\"\"\n if _use_storage_context():\n return (\n self.latest_checkpoint_result.checkpoint\n if self.latest_checkpoint_result\n else None\n )\n\n if self.status == Trial.ERROR:\n checkpoint = (\n self.run_metadata.checkpoint_manager.newest_persistent_checkpoint\n )\n else:\n checkpoint = self.run_metadata.checkpoint_manager.newest_checkpoint\n if checkpoint.dir_or_data is None:\n checkpoint = _TrackedCheckpoint(\n dir_or_data=self.restore_path,\n storage_mode=CheckpointStorage.PERSISTENT,\n )\n return checkpoint\n\n @classmethod\n def generate_id(cls):\n return str(uuid.uuid4().hex)[:8]\n\n @property\n def uses_cloud_checkpointing(self):\n # TODO(justinvyu): This is entangled in the old restore codepaths.\n # Remove this once those are gone.\n if _use_storage_context():\n return False\n\n return bool(self.remote_path)\n\n def reset(self):\n # If there is `default_resource_request` associated with the trainable,\n # clear `resources` and `placement_group_factory`.\n # This is mainly relevant for RLlib tuning jobs, where we save users\n # of the trouble to specify the resources themselves by having some\n # default resources for popular RLlib algorithms.\n trainable_cls = self.get_trainable_cls()\n clear_resources = trainable_cls and trainable_cls.default_resource_request(\n self.config\n )\n placement_group_factory = (\n self.placement_group_factory if not clear_resources else None\n )\n\n checkpoint_config = self.run_metadata.checkpoint_manager.checkpoint_config\n return Trial(\n self.trainable_name,\n config=self.config,\n trial_id=None,\n experiment_path=self._legacy_orig_experiment_path,\n experiment_dir_name=self._legacy_orig_experiment_dir_name,\n evaluated_params=self.evaluated_params,\n experiment_tag=self.experiment_tag,\n placement_group_factory=placement_group_factory,\n stopping_criterion=self.stopping_criterion,\n sync_config=self.legacy_sync_config,\n checkpoint_config=checkpoint_config,\n export_formats=self.export_formats,\n restore_path=self.restore_path,\n trial_name_creator=self.trial_name_creator,\n trial_dirname_creator=self.trial_dirname_creator,\n log_to_file=self.log_to_file,\n max_failures=self.max_failures,\n storage=self.storage,\n )\n\n @Deprecated(\"Replaced by `init_local_path()`\")\n def init_logdir(self):\n # Deprecate: Raise in 2.5, Remove in 2.6\n self.init_local_path()\n\n def init_local_path(self):\n \"\"\"Init logdir.\"\"\"\n if not self.relative_logdir:\n self.relative_logdir = _create_unique_logdir_name(\n str(self.local_experiment_path), self._generate_dirname()\n )\n\n if _use_storage_context():\n # Populate the storage context with the trial dir name we just generated.\n assert self.storage\n self.storage.trial_dir_name = self.relative_logdir\n\n assert self.local_path\n logdir_path = Path(self.local_path)\n max_path_length = _get_max_path_length()\n if len(str(logdir_path)) >= max_path_length:\n logger.warning(\n f\"The path to the trial log directory is too long \"\n f\"(max length: {max_path_length}. \"\n f\"Consider using `trial_dirname_creator` to shorten the path. \"\n f\"Path: {logdir_path}\"\n )\n logdir_path.mkdir(parents=True, exist_ok=True)\n\n self.invalidate_json_state()\n\n def update_resources(self, resources: Union[dict, PlacementGroupFactory]):\n \"\"\"EXPERIMENTAL: Updates the resource requirements.\n\n Should only be called when the trial is not running.\n\n Raises:\n ValueError if trial status is running.\n \"\"\"\n if self.status is Trial.RUNNING:\n raise ValueError(\"Cannot update resources while Trial is running.\")\n\n placement_group_factory = resources\n if isinstance(resources, dict):\n placement_group_factory = resource_dict_to_pg_factory(resources)\n\n self.placement_group_factory = placement_group_factory\n\n self.invalidate_json_state()\n\n def set_ray_actor(self, ray_actor):\n self.temporary_state.ray_actor = ray_actor\n if ray_actor:\n # Do not block here, the result will be gotten when last_result\n # property is accessed\n self._default_result_or_future = ray_actor.get_auto_filled_metrics.remote(\n debug_metrics_only=True\n )\n if not _use_storage_context():\n self.run_metadata.checkpoint_manager.set_delete_fn(\n _CheckpointDeleter(str(self), ray_actor)\n )\n\n def set_location(self, location):\n \"\"\"Sets the location of the trial.\"\"\"\n self.temporary_state.location = location\n\n def set_status(self, status):\n \"\"\"Sets the status of the trial.\"\"\"\n self.status = status\n if status == Trial.RUNNING:\n if self.run_metadata.start_time is None:\n self.run_metadata.start_time = time.time()\n self.invalidate_json_state()\n\n def set_config(self, config):\n self.config = config\n self.invalidate_json_state()\n\n def set_experiment_tag(self, experiment_tag):\n self.experiment_tag = experiment_tag\n self.invalidate_json_state()\n\n @property\n def num_failures(self):\n return self.run_metadata.num_failures\n\n @property\n def num_failures_after_restore(self):\n return self.run_metadata.num_failures_after_restore\n\n @property\n def error_file(self):\n if not self.local_path or not self.run_metadata.error_filename:\n return None\n return os.path.join(self.local_path, self.run_metadata.error_filename)\n\n @property\n def pickled_error_file(self):\n if not self.local_path or not self.run_metadata.pickled_error_filename:\n return None\n return os.path.join(self.local_path, self.run_metadata.pickled_error_filename)\n\n def handle_error(self, exc: Optional[Union[TuneError, RayTaskError]] = None):\n if isinstance(exc, _TuneRestoreError):\n exc = exc.exc\n if self.temporary_state.num_restore_failures >= int(\n os.environ.get(\"TUNE_RESTORE_RETRY_NUM\", 0)\n ):\n # Restore was unsuccessful, try again without checkpoint.\n self.clear_checkpoint()\n self.run_metadata.num_failures += 1\n else:\n self.temporary_state.num_restore_failures += 1\n else:\n self.run_metadata.num_failures += 1\n\n if self.local_path:\n self.run_metadata.error_filename = EXPR_ERROR_FILE\n if isinstance(exc, RayTaskError):\n # Piping through the actual error to result grid.\n self.run_metadata.pickled_error_filename = EXPR_ERROR_PICKLE_FILE\n with open(self.pickled_error_file, \"wb\") as f:\n cloudpickle.dump(exc, f)\n with open(self.error_file, \"a+\") as f:\n f.write(\n \"Failure # {} (occurred at {})\\n\".format(\n self.run_metadata.num_failures, date_str()\n )\n )\n f.write(str(exc) + \"\\n\")\n self.run_metadata.invalidate_cache()\n\n def should_stop(self, result):\n \"\"\"Whether the given result meets this trial's stopping criteria.\"\"\"\n if result.get(DONE):\n return True\n\n for criteria, stop_value in self.stopping_criterion.items():\n if criteria not in result:\n raise TuneError(\n \"Stopping criteria {} not provided in result dict. Keys \"\n \"are {}.\".format(criteria, list(result.keys()))\n )\n elif isinstance(criteria, dict):\n raise ValueError(\n \"Stopping criteria is now flattened by default. \"\n \"Use forward slashes to nest values `key1/key2/key3`.\"\n )\n elif result[criteria] >= stop_value:\n return True\n return False\n\n def should_checkpoint(self):\n \"\"\"Whether this trial is due for checkpointing.\"\"\"\n result = self.last_result or {}\n if result.get(DONE) and self.checkpoint_at_end:\n return True\n return (\n self.checkpoint_freq\n and result.get(TRAINING_ITERATION, 0) % self.checkpoint_freq == 0\n )\n\n def has_checkpoint(self):\n if _use_storage_context():\n return self.checkpoint is not None\n return self.checkpoint.dir_or_data is not None\n\n def clear_checkpoint(self):\n if _use_storage_context():\n if self.latest_checkpoint_result:\n self.latest_checkpoint_result.checkpoint = None\n self.temporary_state.restoring_from = None\n self.run_metadata.invalidate_cache()\n return\n\n self.checkpoint.dir_or_data = None\n self.temporary_state.restoring_from = None\n self.run_metadata.invalidate_cache()\n\n def on_checkpoint(self, checkpoint: Union[_TrackedCheckpoint, _TrainingResult]):\n \"\"\"Hook for handling checkpoints taken by the Trainable.\n\n Args:\n checkpoint: Checkpoint taken.\n \"\"\"\n if _use_storage_context():\n checkpoint_result = checkpoint\n assert isinstance(checkpoint_result, _TrainingResult)\n self.run_metadata.checkpoint_manager.register_checkpoint(checkpoint_result)\n # Increment the checkpoint index to keep the checkpoint index in sync.\n # This index will get restored when the trial is restored and will\n # be passed to the Trainable as the starting checkpoint index.\n self.storage.current_checkpoint_index += 1\n else:\n self.run_metadata.checkpoint_manager.on_checkpoint(checkpoint)\n self.invalidate_json_state()\n self.run_metadata.invalidate_cache()\n\n def on_restore(self):\n \"\"\"Handles restoration completion.\"\"\"\n assert self.is_restoring\n\n if _use_storage_context():\n assert isinstance(self.temporary_state.restoring_from, _TrainingResult)\n\n self.run_metadata.last_result = self.temporary_state.restoring_from.metrics\n self.run_metadata.last_result.setdefault(\"config\", self.config)\n self.temporary_state.restoring_from = None\n self.temporary_state.num_restore_failures = 0\n\n def should_recover(self):\n \"\"\"Returns whether the trial qualifies for retrying.\n\n This is if the trial has not failed more than max_failures. Note this\n may return true even when there is no checkpoint, either because\n `self.checkpoint_freq` is `0` or because the trial failed before\n a checkpoint has been made.\n \"\"\"\n return (\n self.run_metadata.num_failures < self.max_failures\n or self.max_failures < 0\n or (\n self.run_metadata.num_failures == self.max_failures\n and self.temporary_state.num_restore_failures\n < int(os.environ.get(\"TUNE_RESTORE_RETRY_NUM\", 0))\n )\n )\n\n def update_last_result(self, result):\n if self.experiment_tag:\n result.update(experiment_tag=self.experiment_tag)\n\n self.set_location(_Location(result.get(NODE_IP), result.get(PID)))\n self.run_metadata.last_result = result\n self.run_metadata.last_result_time = time.time()\n\n metric_result = self.last_result.copy()\n for remove_metric in DEBUG_METRICS:\n metric_result.pop(remove_metric, None)\n\n for metric, value in flatten_dict(metric_result).items():\n if isinstance(value, Number):\n self.run_metadata.update_metric(\n metric, value, step=result.get(\"training_iteration\")\n )\n\n def get_trainable_cls(self):\n if self.stub:\n return None\n return get_trainable_cls(self.trainable_name)\n\n def get_trial_checkpoints(self) -> List[_TrackedCheckpoint]:\n return self.run_metadata.checkpoint_manager.best_checkpoints()\n\n def is_finished(self):\n return self.status in [Trial.ERROR, Trial.TERMINATED]\n\n @property\n def is_restoring(self):\n return self.temporary_state.restoring_from is not None\n\n @property\n def is_saving(self):\n return self.temporary_state.saving_to is not None\n\n def __repr__(self):\n return self._trainable_name(include_trial_id=True)\n\n def __str__(self):\n return self._trainable_name(include_trial_id=True)\n\n def _trainable_name(self, include_trial_id=False):\n \"\"\"Combines ``env`` with ``trainable_name`` and ``trial_id``.\n\n Can be overridden with a custom string creator.\n \"\"\"\n if self.custom_trial_name:\n return self.custom_trial_name\n\n if \"env\" in self.config:\n env = self.config[\"env\"]\n if isinstance(env, type):\n env = env.__name__\n identifier = \"{}_{}\".format(self.trainable_name, env)\n else:\n identifier = self.trainable_name\n if include_trial_id:\n identifier += \"_\" + self.trial_id\n return identifier.replace(\"/\", \"_\")\n\n def _generate_dirname(self):\n if self.custom_dirname:\n generated_dirname = self.custom_dirname\n else:\n MAX_LEN_IDENTIFIER = int(os.environ.get(\"TUNE_MAX_LEN_IDENTIFIER\", \"130\"))\n generated_dirname = f\"{str(self)}_{self.experiment_tag}\"\n generated_dirname = generated_dirname[:MAX_LEN_IDENTIFIER]\n generated_dirname += f\"_{date_str()}\"\n # This is the file path used by rsync. ['/', '(', ')'] are not allowed.\n return re.sub(\"[/()]\", \"_\", generated_dirname)\n\n def invalidate_json_state(self):\n self._state_json = None\n\n def get_json_state(self) -> Tuple[str, str]:\n if self._state_json is None:\n state = self.__getstate__()\n state.pop(\"run_metadata\", None)\n self._state_json = json.dumps(state, indent=2, cls=TuneFunctionEncoder)\n\n runtime_metadata_json = self.run_metadata.get_json_state()\n\n return self._state_json, runtime_metadata_json\n\n @classmethod\n def from_json_state(cls, json_state: str, stub: bool = False) -> \"Trial\":\n state = json.loads(json_state, cls=TuneFunctionDecoder)\n\n new_trial = Trial(\n state[\"trainable_name\"],\n stub=stub,\n _setup_default_resource=False,\n )\n\n new_trial.__setstate__(state)\n\n return new_trial\n\n def restore_run_metadata(self, run_metadata: str):\n self.run_metadata = _TrainingRunMetadata.from_json_state(run_metadata)\n\n @classmethod\n def from_directory(\n cls, path: Union[str, os.PathLike], stub: bool = False\n ) -> \"Trial\":\n metadata_path = os.path.join(path, TRIAL_STATE_FILENAME)\n if not os.path.exists(metadata_path):\n raise FileNotFoundError(\n f\"Can't restore trial from path: File `{metadata_path}` not found.\"\n )\n\n json_state = Path(metadata_path).read_text()\n return cls.from_json_state(json_state, stub=stub)\n\n def __getstate__(self):\n \"\"\"Memento generator for Trial.\n\n Sets RUNNING trials to PENDING.\n Note this can only occur if the trial holds a PERSISTENT checkpoint.\n \"\"\"\n state = self.__dict__.copy()\n\n for key in self._nonjson_fields:\n state[key] = binary_to_hex(cloudpickle.dumps(state.get(key)))\n\n state.pop(\"temporary_state\", None)\n\n state[\"_state_json\"] = None\n state[\"_default_result_or_future\"] = None\n\n return state\n\n def __setstate__(self, state):\n if state[\"status\"] == Trial.RUNNING:\n state[\"status\"] = Trial.PENDING\n for key in self._nonjson_fields:\n if key in state:\n state[key] = cloudpickle.loads(hex_to_binary(state[key]))\n\n # Ensure that stub doesn't get overriden\n stub = state.pop(\"stub\", True)\n self.__dict__.update(state)\n self.stub = stub or getattr(self, \"stub\", False)\n\n if not self.stub:\n validate_trainable(self.trainable_name)\n\n self.temporary_state = _TemporaryTrialState()\n\n assert self.placement_group_factory\n","sub_path":"python/ray/tune/experiment/trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":47209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"316921468","text":"def format_comments(fstream):\n lines = fstream.readlines()\n for i, line in enumerate(lines):\n if line.endswith('$$\\n'):\n continue\n elif line.count('//'):\n lines[i] = ''.join([lines[i][:-1], ' $$', lines[i][-1]])\n fstream.seek(0)\n for line in lines:\n fstream.write(line)\n","sub_path":"tc/format_comments.py","file_name":"format_comments.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"223722839","text":"from rest_framework import serializers\n\nfrom django.conf import settings as app_settings\nfrom pymongo import MongoClient\nfrom .models import Table\nfrom .utils import connect_to_mongo\n\n\nclass TableSerializer(serializers.HyperlinkedModelSerializer):\n table_uuid = serializers.ReadOnlyField()\n owner = serializers.ReadOnlyField()\n url = serializers.HyperlinkedIdentityField(\n view_name='table-detail',\n lookup_field='table_uuid'\n )\n data = serializers.SerializerMethodField(read_only=True)\n\n class Meta:\n model = Table\n fields = '__all__'\n\n def get_data(self, obj):\n mongo_client = connect_to_mongo()\n connection = mongo_client[obj.name.replace(' ', '_')]\n data = connection.find_one({'table_uuid': str(obj.table_uuid)})\n # temporarily delete _id property\n if data is not None:\n del data['_id']\n return data\n","sub_path":"tables/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"503507906","text":"from pandas import read_csv\nfrom numpy import float64\nimport json\nfrom copy import deepcopy\n\nclass FrequencyTable:\n \"\"\"Represents a frequency table (frequencies of markers vs. alleles). This\n class contains only the metadata associated to the frequency table by default. The\n actual frequency data can be loaded if desired.\n\n Frequency data should follow the following format:\n\n +----------+-----+-----+\n | | A | B |\n +==========+=====+=====+\n | Allele 1 | 0.2 | 0.3 |\n +----------+-----+-----+\n | Allele 2 | 0.3 | 0.2 |\n +----------+-----+-----+\n | ... | ... | ... |\n +----------+-----+-----+\n\n To load a CSV with frequency data for which there is no metadata::\n\n f = FrequencyData('path/to/csv_without_extension', True, total_sample_size=n)\n\n Metadata will be calculated from the metadata arguments you provide and\n from the csv file itself. To persist this metadata to a JSON file::\n\n # saves metadata to filename.json\n f.persist_to()\n\n The following metadata options are supported:\n\n Args:\n name(str): the name of the file sans extension where frequency data is stored\n load_data(str): whether to load actual frequency data or not. Defaults to False. Data may be loaded later with load_data.\n title(str): a descriptive yet short title for the frequency data\n abstract(str): a longer description detailing the source and other characteristics of the data\n total_sample_size(int): The number of people sampled to obtain the relative frequencies of each allele for all the markers. Frequency Table does not support different sample sizes for different markers.\n male_sample_size(int): The number of males sampled to obtain relative frequencies.\n female_sample_size(int): The number of females sampled to obtain relative frequencies.\n \"\"\"\n\n default_metadata = {\n 'name': '',\n 'abstract': '',\n 'total_sample_size': 0,\n 'male_sample_size': 0,\n 'female_sample_size': 0,\n 'frequencies_add_up_to_one': False,\n 'markers': [],\n }\n\n def __init__(self, name, load_data=False, **metadata):\n self.filename = name + '.csv'\n self.file_metadata_extracted = False\n\n\n self._update_metadata(metadata)\n self.metadata['name'] = name\n\n if load_data:\n self.load_data()\n if not self.file_metadata_extracted:\n self.extract_metadata_from_data()\n\n def _update_metadata(self, metadata):\n \"\"\"Replaces default values in the metadata dictionary with the ones\n provided by the user. Additionally, it computes total sample size as\n the sum of male and females sample sizes if provided.\"\"\"\n self.metadata = deepcopy(self.default_metadata)\n for key in self.default_metadata:\n if key in metadata:\n self.metadata[key] = metadata[key]\n\n # procesing for special metadata keys\n if self.metadata['male_sample_size'] > 0 or self.metadata['female_sample_size'] > 0:\n self.metadata['total_sample_size'] = self.metadata['male_sample_size'] + self.metadata['female_sample_size']\n\n if self.metadata['markers']:\n self.file_metadata_extracted = True\n\n def load_data(self, filename=False):\n \"\"\"Loads frequency data from the file asociated with the FrequencyTable\n or from the filename given.\n\n Args:\n filename(str): where to load frequency data from. Defaults to the filename provided on the creation of the object.\"\"\"\n if not filename:\n filename = self.filename\n self.data = read_csv(filename, index_col = 0)\n\n def save_data(self, filename=False):\n \"\"\"Saves frequency data to the CSV file associated with the object or\n to the filename given.\n\n Args:\n filename(str): where to save frequency data to. Defaults to the filename provided on the creation of the object.\"\"\"\n if not filename:\n filename = self.filename\n self.data.to_csv(self.filename)\n\n def extract_metadata_from_data(self):\n \"\"\"Extracts metadata from the frequency file and stores in this\n object. Metadata extracted from the frequency file includes the list of\n analysed markers and wether all allele frequencies add up to one for\n each marker.\"\"\"\n self.metadata['markers'] = list(self.data.columns)\n\n self.metadata['frequencies_add_up_to_one'] = True\n for s in self.data.sum():\n if s != 1.0:\n self.metadata['frequencies_add_up_to_one'] = False\n break\n\n self.file_metadata_extracted = True\n\n def combine(self, other):\n \"\"\"Combines this FrequencyTable with another one. Returns a new\n frequency table with only the common markers. The frequencies in the\n new table are the sum of the frequencies of each combined table,\n weighed by the sample size of each table. Metadata not directly related\n to the frequencies is combined by concatenation.\"\"\"\n if not hasattr(self, 'data'):\n self.load_data()\n\n if not hasattr(other, 'data'):\n other.load_data()\n\n # merge frequency data\n common_markers = self.data.columns & other.data.columns\n new = FrequencyTable(self.metadata['name'] + '+' + other.metadata['name'], load_data=False)\n new.data = (self.data.loc[:, common_markers] * self.metadata['total_sample_size'] \\\n + other.data.loc[:, common_markers] * other.metadata['total_sample_size']).dropna(how=\"all\") \\\n / (new.metadata['total_sample_size'] + other.metadata['total_sample_size'])\n\n # update metadata\n new.extract_metadata_from_data()\n for key in ['total_sample_size', 'male_sample_size', 'female_sample_size']:\n new.metadata[key] = self.metadata[key] + other.metadata[key]\n\n new.metadata['abstract'] = f\"Population data combined from {new.metadata['name']}. Abstracts for each of the sources follow:\" \\\n + \"\\n\" + self.metadata['abstract'] \\\n + \"\\n\" + other.metadata['abstract']\n return new\n\n def to_json(self):\n \"\"\"Returns a JSON string of the metadata of this object.\"\"\"\n return json.dumps(self.metadata)\n\n @classmethod\n def load_from(cls, filename):\n \"\"\"Loads metadata from the given filename. Metadata shall be stored as\n a JSON object akin to the one produced by persist_to().\"\"\"\n with open(filename, 'r') as f:\n read_data = f.read()\n\n metadata = json.loads(read_data)\n print(metadata)\n return cls(**metadata)\n\n def persist_to(self, filename):\n \"\"\"Saves sufficient metadata to rebuild an object (provided the\n frequency file is available) as a json object in the given filename.\"\"\"\n with open(filename, 'w') as f:\n f.write(self.to_json())\n\n def __repr__(self):\n return f\"Frequency table in file {self.filename}\"\n\n def __add__(self, other):\n \"\"\"this + other is an alias for this.combine(other).\"\"\"\n if isinstance(other, FrequencyTable):\n return self.combine(other)\n else:\n return NotImplemented\n","sub_path":"ffreqs/frequency_table.py","file_name":"frequency_table.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"203794977","text":"from injector import inject\n\nfrom domain.connection.services.ConnectionSecretService import ConnectionSecretService\nfrom domain.connection.services.ConnectionServerService import ConnectionServerService\nfrom infrastructor.connection.queue.connectors.KafkaConnector import KafkaConnector\nfrom infrastructor.connection.queue.QueueContext import QueueContext\nfrom infrastructor.connection.queue.connectors.QueueConnector import QueueConnector\nfrom infrastructor.dependency.scopes import IScoped\nfrom infrastructor.logging.SqlLogger import SqlLogger\nfrom models.dao.connection import Connection\nfrom models.enums import ConnectionTypes, ConnectorTypes\n\n\nclass QueueProvider(IScoped):\n @inject\n def __init__(self,\n sql_logger: SqlLogger,\n connection_secret_service: ConnectionSecretService,\n connection_server_service: ConnectionServerService,\n ):\n self.connection_server_service = connection_server_service\n self.connection_secret_service = connection_secret_service\n self.sql_logger = sql_logger\n\n def get_context(self, connection: Connection) -> QueueContext:\n \"\"\"\n Creating Connection\n \"\"\"\n if connection.ConnectionType.Name == ConnectionTypes.Queue.name:\n connection_basic_authentication = self.operation_cache_service.get_connection_basic_authentication_by_connection_id(\n connection_id=connection.Id)\n connection_servers = self.operation_cache_service.get_connection_servers_by_connection_id(\n connection_id=connection.Id)\n connector: QueueConnector = None\n if connection.Queue.ConnectorType.Name == ConnectorTypes.Kafka.name:\n servers = []\n for connection_server in connection_servers:\n server = f\"{connection_server.Host}:{connection_server.Port}\"\n servers.append(server)\n auth = None\n if ((connection.Queue.Protocol is not None and connection.Queue.Protocol != '') and (\n connection.Queue.Mechanism is not None and connection.Queue.Mechanism != '') and (\n connection_basic_authentication.User is not None and connection_basic_authentication.User != '') and (\n connection_basic_authentication.Password is not None and connection_basic_authentication.Password != '')):\n auth = {\n 'security_protocol': connection.Queue.Protocol,\n 'sasl_mechanism': connection.Queue.Mechanism,\n 'sasl_plain_username': connection_basic_authentication.User,\n 'sasl_plain_password': connection_basic_authentication.Password\n }\n connector = KafkaConnector(servers=servers, auth=auth)\n if connector is not None:\n queue_context: QueueContext = QueueContext(connector=connector)\n return queue_context\n else:\n raise Exception(f\"{connection.Queue.ConnectorType.Name} connector type not supported\")\n\n else:\n raise Exception(f\"{connection.ConnectionType.Name} connection type not supported\")\n","sub_path":"src/process/infrastructor/connection/queue/QueueProvider.py","file_name":"QueueProvider.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"153094969","text":"# -*- coding:utf-8 -*-\n\n\n#\n# Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to any one of the place in the array A indexed i+1, i+2, …, i+B if this place can be jumped to. Also, if you step on the index i, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the place indexed i in the array.\r\n#\n#\n#\n# Now, you start from the place indexed 1 in the array A, and your aim is to reach the place indexed N using the minimum coins. You need to return the path of indexes (starting from 1 to N) in the array you should take to get to the place indexed N using minimum coins.\r\n#\n#\n#\n# If there are multiple paths with the same cost, return the lexicographically smallest such path.\r\n#\n#\n# If it's not possible to reach the place indexed N then you need to return an empty array.\r\n#\n#\n# Example 1:\r\n#\n# Input: [1,2,4,-1,2], 2\r\n# Output: [1,3,5]\r\n#\n#\n#\n# Example 2:\r\n#\n# Input: [1,2,4,-1,2], 1\r\n# Output: []\r\n#\n#\n#\n# Note:\r\n#\n# Path Pa1, Pa2, ..., Pan is lexicographically smaller than Pb1, Pb2, ..., Pbm, if and only if at the first i where Pai and Pbi differ, Pai < Pbi; when no such i exists, then n < m.\r\n# A1 >= 0. A2, ..., AN (if exist) will in the range of [-1, 100]. \r\n# Length of A is in the range of [1, 1000].\r\n# B is in the range of [1, 100].\r\n#\n#\n\n\nclass Solution(object):\n def cheapestJump(self, A, B):\n \"\"\"\n :type A: List[int]\n :type B: int\n :rtype: List[int]\n \"\"\"\n n = len(A)\n if A[n - 1] < 0: return []\n if n == 1:\n if A[0] < 0: return []\n else: return [1]\n f = [float('inf') for _ in range(n)]\n _next = [-1 for _ in range(n)]\n f[n - 1] = A[n - 1]\n for i in range(n - 1, -1, -1):\n if A[i] == -1: continue\n for k in range(1, B + 1):\n cur = i + k\n if cur >= n: continue\n if f[cur] < f[i]:\n f[i] = f[cur]\n _next[i] = cur\n f[i] += A[i]\n print(f)\n print(_next)\n res = []\n cur = 0\n if f[0] == float('inf'): return []\n while cur != -1:\n res.append(cur + 1)\n cur = _next[cur]\n return res\n \n","sub_path":"656-coin-path/coin-path.py","file_name":"coin-path.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"296463936","text":"from django.db import models\n\nfrom core.models import Authored, Titled\nfrom core.decorators import non_editable_fields\n\nfriendship = {\n 1: 'Первый друг',\n 10: 'Дружелюбный',\n 50: 'Братишка',\n 100: 'Филантроп',\n 500: 'Другоман',\n 1000: 'Другофил',\n}\n\nlikes = {\n 1: 'Первый лайк',\n 10: 'Интересный пост!',\n 50: 'Популярный',\n 100: 'Соточка',\n 500: 'Создатель мемов',\n 1000: 'Лайкодрочер',\n}\n\ncomments = {\n 1: 'Первый коммент',\n 10: 'Интересный пост!',\n 50: 'Интересное обсуждение!',\n 100: 'Срач',\n 500: 'Мегасрач',\n 1000: 'Разжигатель',\n}\n\n\n@non_editable_fields('author_id')\nclass Achievement(Authored, Titled):\n content = models.TextField(verbose_name='Содержание')\n\n class Meta:\n verbose_name = 'Достижение'\n verbose_name_plural = 'Достижения'\n unique_together = (('author', 'title'),)\n\n def __str__(self):\n return '{0}: достижение {1}'.format(self.author, self.title)\n","sub_path":"achievements/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"584413906","text":"# This is a Day 2 Project!\nprint(\"Welcome to the tip calculator.\")\n\n#Total bill\ntotal_bill = input(\"What is the total bill?: $\")\nint_total_bill = float(total_bill)\n\n#Tip Percentage\ntip_percentage = input(\"What percentage tip would you like to give? \")\nint_tip_percentage = int(tip_percentage)\n\n#Total tip\ntotal_tip = int_total_bill * (int_tip_percentage / 100)\n\n#Total After Tip\ntotal_after_tip = int_total_bill + total_tip\n\n#Bill Split\nbill_split = input(\"How many people to split the bill? \")\nint_bill_split = int(bill_split)\n\n#Each Person Payment\neach_payment = total_after_tip / int_bill_split\nround_each_payment = \"{:.2f}\".format(each_payment)\n# round_each_payment = round(each_payment, 2)\n\n#Result\nend_result = f\"Each person should pay : ${round_each_payment}\"\nprint(end_result)","sub_path":"Tip Calculator - Day 2.py","file_name":"Tip Calculator - Day 2.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"248647258","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[250]:\n\n\nimport csv\nimport requests\nimport json\n\n\n# In[251]:\n\n\nheaders = {\n\t'Accept': 'application/json, text/javascript, */*; q=0.01',\n\t'Accept-Encoding': 'gzip, deflate',\n\t'Accept-Language': 'zh-CN,zh;q=0.9',\n\t'Connection': 'keep-alive',\n\t'Content-Length': '44',\n\t'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n\t'Cookie': 'JSE=USd5H4MJMq; JSESSIONID=575434700FFE32E7E8BDCCF8F040A1AE',\n\t'Host': 'www.noi.cn',\n\t'Origin': 'http://www.noi.cn',\n\t'Referer': 'http://www.noi.cn/awardsearch.html',\n\t'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',\n\t'X-Requested-With': 'XMLHttpRequest'}\n\nurl = 'http://www.noi.cn/awards.AwardSearch.dt'\n\ndef data(name) : \n\treturn{\n\t'cmd': 'search',\n\t'key': 'name',\n\t'value': name}\n\n\nf = csv.reader(open('raw_data.csv'))\nout_file = open('result.csv', 'w')\nout = csv.writer(out_file)\n\n\n# In[252]:\n\n\nmatch = {\n '高一' : 1,\n '高二' : 2,\n '高三' : 3,\n '初三' : 0,\n '初二' : -1,\n '初一' : -2,\n '初中' : -10,\n '小学' : -10,\n\t'初四' : -10\n}\n\n\n# In[253]:\n\n\ndef get(str):\n a = \"\"\n for i in range(len(str)):\n if(str[i] >= '0' and str[i] <= '9'):\n a += str[i]\n return int(a)\n\n\n# In[254]:\n\n\ndef get_awards(name, grad_year):\n current_year = grad_year\n r = requests.post(url, headers = headers, data = data(name))\n a = json.loads(r.text)\n lst = []\n for i in a:\n qaq = a[i]\n if(isinstance(qaq, str)):\n break\n if (\"复赛提高组\" in qaq['compname']) or ((\"NOI20\" in qaq['compname']) and (not(\"冬令营\" in qaq['compname']))):\n name = qaq['compname']\n year = get(name)\n bias = 0\n if not (\"NOIP\" in qaq['compname']):\n bias += 1\n if(4 - bias - current_year + year != match[qaq['grade']]):\n continue\n if(\"复赛提高组\" in qaq['compname'] and qaq['award'] != '一等奖'):\n continue\n lst.append(qaq['compname'] + qaq['award'])\n return lst\n\n\n# In[255]:\n\n\nfor row in f:\n this_name = row[1]\n award = get_awards(this_name, 2016)\n if award:\n print([row[0], row[1], row[3], award])\n out.writerow([row[0], row[1], row[3], award])\n\n","sub_path":"major.py","file_name":"major.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"242799067","text":"#!/usr/local/bin/python3\n\nfrom bs4 import BeautifulSoup\nimport re\nimport urllib2\nimport requests\nfrom pprint import pprint\nimport os,sys\nimport html2markdown\n\ninvalid_tags = ['div', 'span']\n\nbaseUrl = \"https://sites.google.com\"\n\nurl = \"site/mytechnicalcollection/os\"\npage = requests.get(os.path.join(baseUrl,url))\n\nsoup = BeautifulSoup(page.content,features=\"lxml\")\nsubpages = soup.find('div',{\"class\":\"sites-subpages\"}).find_all('span')\n\ndel subpages[0]\n\nfor page in subpages:\n topicUrl = page.a['href']\n url = \"https://sites.google.com\"+topicUrl\n subpage = requests.get(url)\n soup = BeautifulSoup(subpage.content,features=\"lxml\")\n \n content = soup.find(attrs={\"role\": \"main\"}).table\n\n\n for tag in content.findAll(True):\n for attr in [attr for attr in tag.attrs]:\n print(attr)\n if not attr in ['src']:\n del tag[attr]\n\n for row in content.find_all(\"tr\"):\n for td in row.find_all(\"td\"):\n for tag in invalid_tags: \n for match in td.findAll(tag):\n match.replaceWithChildren()\n # for attribute in [\"class\", \"id\", \"name\", \"style\"]:\n # del td[attribute]\n\n\n print(html2markdown.convert(str(content)))\n sys.exit()\n \n\n #\n #print(content)\n\n\n","sub_path":"Trunk/2019_Spring/Resources/OS_Topics/grab_data.py","file_name":"grab_data.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"419747621","text":"from Cell import Cell\nimport numpy as np\nimport random\nimport math\nimport fractions\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom decimal import *\n\nclass Tumor_cell(Cell):\n dr_type = 0\n @classmethod\n def receive_value(cls, AVERAGE, DISPERSION, AROUND, WEIGHT1, WEIGHT2, MTRATE, DRUGTIMES, EFFECT):\n Cell.AVERAGE = AVERAGE\n Cell.DISPERSION = DISPERSION\n Cell.AROUND = AROUND\n Cell.WEIGHT1 = WEIGHT1\n Cell.WEIGHT2 = WEIGHT2\n Cell.MTRATE = MTRATE\n Cell.K1 = Cell.AVERAGE * 8 * Cell.AROUND * (Cell.AROUND + 1)\n Cell.K2 = Cell.AVERAGE * 8 * Cell.AROUND * (Cell.AROUND + 1) * (Cell.WEIGHT1 + 1)\n Cell.KM = (2 * Cell.AROUND + 1) ** 2 - 1\n Cell.EFFECT = EFFECT\n Cell.drtime_list = DRUGTIMES.split(\",\")\n Cell.resicount = 0\n Cell.DR_STRTIME = 0\n Cell.DR_DURATION = int(Cell.drtime_list[0])\n Cell.DR_INTERVAL = int(Cell.drtime_list[1])\n\n def __init__(self, i, j):\n super().__init__(i, j)\n self.mutation_id = 1\n self.resistflag = 0\n self.enemynum = 0\n self.type = 1\n self.drdeath = 0\n self.driver_mutation = 0\n self.driverflag = 0\n self.driver_type = 0\n\n\n @classmethod\n def set_first_cell(cls, field, on, celllist):\n first_cell = Tumor_cell(on, on)\n first_cell.id = 0\n first_cell.type = 1\n first_cell.waittime = 1\n first_cell.count = 0\n first_cell.proliferation = 0\n celllist.append(first_cell)\n field[first_cell.i, first_cell.j] = first_cell.id\n\n def prolife(self, field, celllist, timedic, driver_list):\n ni = self.i + Cell.mi\n nj = self.j + Cell.mj\n cell_new = Tumor_cell(ni, nj)\n cell_new.id = len(celllist)\n cell_new.mutation_id = self.mutation_id * 2 + 1\n self.mutation_id = self.mutation_id * 2\n timedic[self.mutation_id] = self.count\n timedic[cell_new.mutation_id] = self.count\n self.count = 0\n self.proliferation = 0\n cell_new.driver_mutation = self.driver_mutation\n cell_new.type = self.type\n cell_new.driver_type = self.driver_type\n\n if self.driver_mutation == 0 and self.type == 1:\n self.driverflag = np.random.choice([1, 0], p=[Cell.MTRATE, 1 - Cell.MTRATE])\n if self.driverflag == 1:\n self.type = 2\n self.driver_mutation = 1\n driver_list.append(self.mutation_id)\n Tumor_cell.dr_type += 1\n self.driver_type = Tumor_cell.dr_type\n self.driverflag = 0\n else:\n pass\n\n if cell_new.driver_mutation == 0 and cell_new.type == 1:\n cell_new.driverflag = np.random.choice([1, 0], p=[Cell.MTRATE, 1 - Cell.MTRATE])\n if cell_new.driverflag == 1:\n cell_new.type = 2\n cell_new.driver_mutation = 1\n driver_list.append(cell_new.mutation_id)\n Tumor_cell.dr_type += 1\n cell_new.driver_type = Tumor_cell.dr_type\n cell_new.driverflag = 0\n else:\n pass\n\n cell_new.move(field, celllist)\n celllist.append(cell_new)\n\n def prolife_simple(self, field, celllist):\n ni = self.i + Cell.mi\n nj = self.j + Cell.mj\n cell_new = Tumor_cell(ni, nj)\n cell_new.id = len(celllist)\n self.count += 1\n cell_new.mutation_id = self.mutation_id * 2 + 1\n self.mutation_id = self.mutation_id * 2\n cell_new.count = self.count\n self.proliferation = 0\n cell_new.type = self.type\n\n if self.type == 1:\n self.resistflag = np.random.choice([1, 0], p=[Cell.MTRATE, 1 - Cell.MTRATE])\n if self.resistflag == 1:\n Cell.resicount += 1\n self.type = 2\n self.resistflag = 0\n\n cell_new.move(field, celllist)\n celllist.append(cell_new)\n\n @classmethod\n def radial_prolife_up(cls, field, on, func, celllist, timedic, driver_list):\n if celllist[field[on, on]].proliferation == 1:\n getattr(celllist[field[on, on]], func)(field)\n celllist[field[on, on]].prolife(field, celllist, timedic, driver_list)\n for r in range(1, on):\n a = field[on - r, on - r : on + r + 1].flatten()\n a = list(a[a != -1])\n for i in a:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n b = field[on - r + 1 : on + r + 1, on + r].flatten()\n b = list(b[b != -1])\n for i in b:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n c = field[on + r, on + r - 1: on - r -1 : -1].flatten()\n c = list(c[c != -1])\n for i in c:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n d = field[on + r - 1 : on - r : -1, on - r].flatten()\n d = list(d[d != -1])\n for i in d:\n if celllist[i].proliferation == 1:\n getattr(celllist[i], func)(field)\n celllist[i].prolife(field, celllist, timedic, driver_list)\n\n def count_around(self, heatmap):\n self.num = 0\n self.enemynum = 0\n if self.dead == 0:\n arheatmap = heatmap[self.i - Cell.AROUND:self.i + Cell.AROUND + 1, self.j - Cell.AROUND:self.j + Cell.AROUND + 1].flatten()\n nozeroheat = arheatmap[arheatmap != 0]\n self.num = -1 + len(nozeroheat[nozeroheat == self.type])\n self.enemynum = len(nozeroheat[nozeroheat != self.type])\n\n def mortal1(self, field):\n if self.enemynum <= Cell.K1 and self.dead == 0:\n nE = (self.num + self.enemynum) / Cell.K1\n nE = round(nE, 3)\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n def mortal2(self, field):\n if self.dead == 0:\n if self.type == 1:\n nE = (self.num + self.enemynum * Cell.WEIGHT2) / Cell.K1\n nE = round(nE, 3)\n if self.type == 2:\n nE = (self.num + self.enemynum * Cell.WEIGHT1) / Cell.K1\n nE = round(nE, 3)\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n def drugged(self, t):\n if len(Cell.drtime_list) != 0 and self.dead == 0:\n if t >= int(Cell.drtime_list[0]) and t < int(Cell.drtime_list[1]):\n if self.type == 1:\n dens = 1 - (self.num + self.enemynum) / Cell.KM\n self.drdeath = dens * Cell.EFFECT\n if t == int(Cell.drtime_list[1]):\n if self.type == 1:\n self.drdeath = 0\n\n @classmethod\n def prepare_drug(cls, t):\n Cell.DR_STRTIME = t\n\n def drugged_infinity(self, t):\n if t >= Cell.DR_STRTIME and t < Cell.DR_STRTIME + Cell.DR_DURATION:\n if self.type == 1:\n dens = 1 - (self.num + self.enemynum) / Cell.KM\n self.drdeath = dens * Cell.EFFECT\n if t == Cell.DR_STRTIME + Cell.DR_DURATION:\n if self.type == 1:\n self.drdeath = 0\n\n def drugged_infinity_continued(self):\n if self.type == 1:\n dens = 1 - (self.num + self.enemynum) / Cell.KM\n self.drdeath = dens * Cell.EFFECT\n\n @classmethod\n def drtime_adjust(cls, t):\n if t == Cell.DR_STRTIME + Cell.DR_DURATION:\n Cell.DR_STRTIME += Cell.DR_INTERVAL + Cell.DR_DURATION\n\n @classmethod\n def drtime_list_adjust(cls, t):\n if len(Cell.drtime_list) != 0:\n if t == int(Cell.drtime_list[1]):\n del Cell.drtime_list[0:2]\n\n def mortal1_drug(self, field):\n if self.dead == 0:\n nE = (self.num + self.enemynum) / Cell.K1\n nE = round(nE, 3)\n if self.type == 1:\n nE += self.drdeath\n if nE >= 1:\n nE = 1\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n def mortal2_drug(self, field):\n if self.dead == 0:\n if self.type == 1:\n nE = (self.num + self.enemynum * Cell.WEIGHT2) / Cell.K1 + self.drdeath\n nE = round(nE, 3)\n if nE >= 1:\n nE = 1\n if self.type == 2:\n nE = (self.num + self.enemynum * Cell.WEIGHT1) / Cell.K1\n nE = round(nE, 3)\n self.deathflag = np.random.choice([0, 1], p=[1 - nE, nE])\n if self.deathflag == 1:\n self.dead = 1\n field[self.i, self.j] = -1\n self.deathflag = 0\n else:\n pass\n\n @classmethod\n def list_adjust(cls, driver_list):\n driver_list.sort()\n\n @classmethod\n def make_idlist(cls, field, celllist):\n Tumor_cell.idlist = []\n refid = np.random.choice(field[field > -1], 256, replace=False)\n for i in refid:\n Tumor_cell.idlist.append(celllist[i].mutation_id)\n","sub_path":"python/Tumorcell_compe.py","file_name":"Tumorcell_compe.py","file_ext":"py","file_size_in_byte":9858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"626799379","text":"import connexion\nimport six\n\nfrom swagger_server import util\nimport subprocess\nfrom connexion import NoContent\n\ndef run_cmd(args_list):\n \"\"\"\n run linux commands\n \"\"\"\n temp = args_list.split(\" \")\n temp = [ i for i in temp if i!='']\n print('Running system command : {0}'.format(' '.join(temp)))\n proc = subprocess.Popen(temp, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n s_output, s_err = proc.communicate()\n s_return = proc.returncode\n if s_return == 0:\n print (\"Command executed successfully \")\n retVal=400\n else:\n print(s_output)\n retVal=401\n return retVal\n\n\ndef trigger_ingestion(feedname): # noqa: E501\n \"\"\"Trigger a data ingestion rule\n\n # noqa: E501\n\n :param feedname: Feedname for which data ingestion needs to be triggered\n :type feedname: str\n\n :rtype: None\n \"\"\"\n command = \"python3 /home/etl/ETL/Trail_code/ETL_Ingestion.py \" + feedname\n ret_val = run_cmd(command)\n return 'data ingestion completed', ret_val\n","sub_path":"ETL_Swagger_Praveen/praveen/swag3/swagger_server/controllers/trigger_controller.py","file_name":"trigger_controller.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"292162574","text":"#!/usr/bin/env python\n\nimport logging\nfrom subprocess import Popen, PIPE\nimport sys\n\nfrom magi.testbed import testbed\nfrom magi.util import helpers\nfrom magi.util.agent import DispatchAgent\nfrom magi.util.processAgent import initializeProcessAgent\n\nlog = logging.getLogger()\n\nclass link_up_down(DispatchAgent):\n \n def __init__(self):\n DispatchAgent.__init__(self)\n\n #there should be a delay node between the two nodes connected by the link for this up/down to work.\n # 'timing' is in seconds - 'timing' is relative to the time the event is called \n def link_up(self, msg, dest):\n functionName = self.link_up.__name__\n helpers.entrylog(log, functionName, locals())\n \n intf = self.node2Intf(dest)\n \n cmd = \"ifconfig %s up\" %(intf)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link to node '\" + dest + \"' brought up.\")\n else:\n log.error(stderr)\n log.error(\"Error in bringing link to node '\" + dest + \"' up. Error code %d\" %(returncode))\n \n return True\n\n def link_down(self, msg, dest):\n functionName = self.link_down.__name__\n helpers.entrylog(log, functionName, locals())\n \n intf = self.node2Intf(dest)\n \n cmd = \"ifconfig %s down\" %(intf)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link to node '\" + dest + \"' put down.\")\n else:\n log.error(stderr)\n log.error(\"Error in putting link to node '\" + dest + \"' down. Returncode %d\" %(returncode))\n \n return True\n\n def node2Intf(self, dest):\n topoGraph = testbed.getTopoGraph()\n src = testbed.getNodeName()\n linkname = topoGraph[src][dest]['linkName']\n srcLinks = topoGraph.node[src]['links']\n try:\n ip = srcLinks[linkname]['ip']\n return testbed.getInterfaceInfo(ip).name\n except Exception:\n raise Exception(\"Invalid information. Mostly no direct link to destination '%s'.\" %(dest))\n \n \n def link_up_tevc(self, msg, linkName, timing):\n functionName = self.link_up.__name__\n helpers.entrylog(log, functionName, locals())\n \n if timing == 0:\n timing = \"now\"\n else:\n timing = \"+\" + str(timing)\n \n cmd = \"/usr/testbed/bin/tevc -e %s %s %s up\" %(testbed.eid, timing, linkName)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link '\" + linkName + \"' brought up.\")\n else:\n log.error(stderr)\n log.error(\"Error in bringing link '\" + linkName + \"' up. Error code %d\" %(returncode))\n \n return True\n\n def link_down_tevc(self, msg, linkName, timing):\n functionName = self.link_down.__name__\n helpers.entrylog(log, functionName, locals())\n \n if timing == 0:\n timing = \"now\"\n else:\n timing = \"+\" + str(timing)\n \n cmd = \"/usr/testbed/bin/tevc -e %s %s %s down\" %(testbed.eid, timing, linkName)\n log.info(\"Running cmd: %s\" %(cmd))\n \n process = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)\n returncode = process.wait()\n stdout, stderr = process.communicate()\n \n if returncode == 0:\n log.info(stdout)\n log.info(\"Link '\" + linkName + \"' put down.\")\n else:\n log.error(stderr)\n log.error(\"Error in putting link '\" + linkName + \"' down. Returncode %d\" %(returncode))\n \n return True\n\n# the getAgent() method must be defined somewhere for all agents.\n# The Magi daemon invokes this method to get a reference to an\n# agent. It uses this reference to run and interact with an agent\n# instance.\ndef getAgent(**kwargs):\n agent = link_up_down()\n agent.setConfiguration(None, **kwargs)\n return agent\n\n# In case the agent is run as a separate process, we need to\n# create an instance of the agent, initialize the required\n# parameters based on the received arguments, and then call the\n# run method defined in DispatchAgent.\nif __name__ == \"__main__\":\n agent = link_up_down()\n kwargs = initializeProcessAgent(agent, sys.argv)\n agent.setConfiguration(None, **kwargs)\n agent.run()\n","sub_path":"link_up_down/link_up_down.py","file_name":"link_up_down.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"83946814","text":"import numpy as np\nimport warnings\nfrom galaxy_ml.preprocessors import TDMScaler\n\n\nwarnings.simplefilter('ignore')\n\n\nX = [[1., -2., 2.],\n [-2., 1., 3.],\n [4., 1., -2.]]\n\n\ndef test_self_transform():\n scaler = TDMScaler()\n scaler.fit(X)\n got = scaler.transform(X)\n\n assert np.array_equal(X, got), got\n","sub_path":"galaxy_ml/tests/test_tdmscaler.py","file_name":"test_tdmscaler.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"436961273","text":"import math\nimport numpy as np\nclass Frame():\n def __init__(self, img=None, list_of_persons=list(), list_of_groups=list(), list_of_vehicles=list(),\n list_of_zones=list(), image_height=1080, image_width=1920, bboxes=list()):\n self.image = img\n self.list_of_persons = list_of_persons\n self.list_of_groups = list_of_groups\n self.list__of_vehicles = list_of_vehicles\n self.time = None\n self.list_of_zones = list_of_zones\n self.image_width = image_width\n self.image_height = image_height\n self.list_of_bboxes = bboxes\n\n def filter_bbox_human(self, list_of_bboxes):\n list_of_persons = list()\n for elem in list_of_bboxes:\n if elem is not \"\" and elem[-1] is \"0\":\n list_of_persons.append(list(map(int, elem.split(\",\")[:-1])))\n self.list_of_persons = list_of_persons\n\n def filter_bbox_vehicles(self, list_of_bboxes):\n list_of_persons = list()\n for elem in list_of_bboxes:\n if elem is not \"\" and elem[-1] is \"5\":\n list_of_persons.append(list(map(int, elem.split(\",\")[:-1])))\n self.list__of_vehicles = list_of_persons\n\n def check_for_neighbours(self):\n x_min, y_min, x_max, y_max = 0, 1, 2, 3\n groups = list()\n for person_idx in range(len(self.list_of_persons)):\n person1 = self.list_of_persons[person_idx]\n for person_to_comp_idx in range(len(self.list_of_persons)):\n if person_idx is person_to_comp_idx:\n continue\n else:\n person1_range_top = person1[y_min] - int((person1[y_max] - person1[y_min]) / 2)\n person1_range_bottom = person1[y_max] + int((person1[y_max] - person1[y_min]) / 2)\n person1_range_left = int((person1[x_min] - (person1[x_max] - person1[x_min])) * 1.05)\n person1_range_right = int((person1[x_max] + (person1[x_max] - person1[x_min])) * 1.05)\n person2 = self.list_of_persons[person_to_comp_idx]\n\n # check whether the neighbour is in the near of the bottom or top point of person1\n if (person1_range_top >= 0) and person1_range_top <= person2[y_min] <= person1[y_min] or \\\n (person1_range_bottom <= self.image_height) and person1_range_bottom <= person2[y_max] <= \\\n person1[\n y_max]:\n\n # check whether the neighbour is in the near of the left or right point of person1\n if (person1_range_right <= self.image_width) and person1[x_min] <= person2[\n x_min] <= person1_range_right or \\\n (person1_range_left >= 0) and person1_range_left <= person2[2] <= person1[x_min]:\n is_already_in_group = False\n if len(groups) > 0:\n for g in groups:\n if person_idx in g.members and person_to_comp_idx not in g.members:\n g.members.append(person_to_comp_idx)\n g.update_min_max_values_of_group([self.list_of_persons[person_to_comp_idx]])\n is_already_in_group = True\n break\n if not is_already_in_group:\n new_g = Group(person_idx)\n new_g.members.append(person_idx)\n new_g.members.append(person_to_comp_idx)\n new_g.update_min_max_values_of_group(\n [self.list_of_persons[person_idx], self.list_of_persons[person_to_comp_idx]])\n groups.append(new_g)\n self.list_of_groups = groups\n\n\nclass Person():\n def __init__(self, id, bbox):\n self.id = id\n self.bbox = bbox\n self.prev_bbox = bbox\n self.path = list()\n self.avg_speed = None\n\n def is_falling(self):\n # bbox = (xmin, ymin, xmax, ymax)\n return self.bbox[2] - self.bbox[0] < self.bbox[3] - self.bbox[1]\n\n def calculate_avg_speed(self):\n speed_between_frame = list()\n if len(self.path) > 1:\n for p in range(len(self.path)):\n dist = math.hypot(self.path[p][0] - self.path[p - 1][0], self.path[p][1] - self.path[p - 1][1])\n speed_between_frame.append(dist)\n arr = np.asarray(speed_between_frame)\n self.avg_speed = arr.mean()\n\n def update_person(self,bbox,keep_bbox=False ):\n self.prev_bbox = self.bbox\n if not keep_bbox:\n self.bbox = bbox\n middle_of_foot = (bbox[0] + ((bbox[1]-bbox[0])/2), bbox[3])\n self.path.append(middle_of_foot)\n self.calculate_avg_speed()\n\n\n\nclass Car():\n def __init__(self, id, bbox):\n self.id = id\n self.bbox = bbox\n self.path = list()\n self.avg_speed = None\n\n def calculate_avg_speed(self):\n speed_between_frame = list\n for p in range(len(self.path)):\n dist = math.hypot(self.path[p+1][0] - self.path[p][0], self.path[p+1][1] - self.path[p][1])\n speed_between_frame.append(dist)\n arr = np.asarray(speed_between_frame)\n self.avg_speed = arr.mean()\n\n def update_car(self,bbox,keep_bbox=False ):\n self.prev_bbox = self.bbox\n if not keep_bbox:\n self.bbox = bbox\n middle_of_foot = (bbox[0] + ((bbox[1]-bbox[0])/2), bbox[3])\n self.path.append(middle_of_foot)\n self.calculate_avg_speed()\n\n\n \n\n\n\n\nclass Group():\n def __init__(self, id):\n self.id = id\n self.members = list()\n self.min_x = 20000\n self.min_y = 20000\n self.max_x = 0\n self.max_y = 0\n self.bbox = [self.min_x, self.min_y, self.max_x, self.max_y]\n\n def update_min_max_values_of_group(self, list_of_bboxes):\n for elem in list_of_bboxes:\n if elem[0] < self.min_x:\n self.min_x = elem[0]\n if elem[1] < self.min_y:\n self.min_y = elem[1]\n if elem[2] > self.max_x:\n self.max_x = elem[2]\n if elem[3] > self.max_y:\n self.max_y = elem[3]\n\n self.bbox = [self.min_x, self.min_y, self.max_x, self.max_y]\n","sub_path":"helpers/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"476571129","text":"\"\"\"\nCopyright 2020, Institute for Systems Biology\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nimport io\nimport json\nimport os\nimport sys\nimport time\n\nimport requests\nimport yaml\nfrom google.api_core.exceptions import NotFound\nfrom google.cloud import bigquery, storage, exceptions\n\n\n# GETTERS - YAML CONFIG\n\n\ndef get_field_groups(api_params):\n \"\"\"Get field group list from build master table yaml config for GDC.\n\n :param api_params: api param object from yaml config\n :return: list of expand field groups\n \"\"\"\n if 'FIELD_GROUPS' not in api_params:\n has_fatal_error('FIELD_GROUPS not in api_params (check yaml config file)')\n return \",\".join(list(api_params['FIELD_GROUPS']))\n\n\ndef get_required_fields(api_params, fg):\n \"\"\"Get list of required fields (used to create schema and load values into BQ table).\n\n :param api_params: api param object from yaml config\n :param fg: name of field group for which to retrieve required fields\n :return: list of required fields (currently only returns fg's id key)\n \"\"\"\n field_config = api_params['FIELD_CONFIG']\n\n if fg in field_config and 'id_key' in field_config[fg]:\n # this is a single entry list of the moment\n return [get_field_key(fg, field_config[fg]['id_key'])]\n\n return None\n\n\ndef get_column_order_one_fg(api_params, fg):\n \"\"\"Get field/column order list associated with given field group from yaml config.\n\n :param api_params: api param object from yaml config\n :param fg: field group for which to retrieve field/column order list\n :return: field group's column order list\n \"\"\"\n if fg not in api_params['FIELD_CONFIG']:\n has_fatal_error(\"'{}' not found in FIELD_CONFIG in yaml config\".format(fg))\n\n fg_params = api_params['FIELD_CONFIG'][fg]\n\n if not fg_params or 'column_order' not in fg_params:\n has_fatal_error(\"No order for field group {} in yaml.\".format(fg), KeyError)\n\n # return full field key, in order, for given field_grp\n return [get_field_key(fg, field) for field in fg_params['column_order']]\n\n\ndef get_excluded_field_groups(api_params):\n \"\"\"Get a list of field groups (via yaml config) to exclude from the final tables.\n Currently used in order to exclude fgs that would otherwise create duplicate columns\n when merging fgs into a smaller # of tables, WHILE not utilizing fg prefixes\n to create unique names (which is undesirable for web app integration, for instance).\n\n :param api_params: api param object from yaml config\n :return: list of field groups to exclude\n \"\"\"\n if 'FG_CONFIG' not in api_params or not api_params['FG_CONFIG']:\n has_fatal_error('FG_CONFIG not in api_params, or is empty', KeyError)\n if 'excluded_fgs' not in api_params['FG_CONFIG']:\n has_fatal_error('excluded_fgs not found in not in FG_CONFIG', KeyError)\n\n return api_params['FG_CONFIG']['excluded_fgs']\n\n\ndef get_excluded_fields_all_fgs(api_params, fgs, is_webapp=False):\n \"\"\"Get a list of fields for each field group to exclude from the tables\n from yaml config (api_params['FIELD_CONFIG']['excluded_fields'] or\n api_params['FIELD_CONFIG']['app_excluded_fields'] for the web app).\n\n :param api_params: api param object from yaml config\n :param fgs: list of expand field groups included from API call\n :param is_webapp: is script currently running for 'create_webapp_tables' step?\n :return: set of fields to exclude\n \"\"\"\n if 'FIELD_CONFIG' not in api_params or not api_params['FIELD_CONFIG']:\n has_fatal_error('FIELD_CONFIG not in api_params, or is empty', KeyError)\n\n excluded_list_key = 'app_excluded_fields' if is_webapp else 'excluded_fields'\n\n exclude_fields = set()\n\n for fg in fgs:\n if fg not in api_params['FIELD_CONFIG']:\n has_fatal_error('{} not found in not in FIELD_CONFIG'.format(fg), KeyError)\n elif not api_params['FIELD_CONFIG'][fg]:\n continue\n elif excluded_list_key not in api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"One of the excluded params missing from YAML.\", KeyError)\n elif not api_params['FIELD_CONFIG'][fg][excluded_list_key]:\n continue\n\n for field in api_params['FIELD_CONFIG'][fg][excluded_list_key]:\n exclude_fields.add(get_field_key(fg, field))\n\n return exclude_fields\n\n\ndef get_excluded_fields_one_fg(api_params, fg, is_webapp=False):\n \"\"\"Get excluded fields for given field group (pulled from yaml config file).\n\n :param api_params: api param object from yaml config\n :param fg: field group for which to retrieve excluded fields\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: list of excluded fields associated with field group 'fg' in yaml config\n \"\"\"\n if 'FIELD_CONFIG' not in api_params:\n has_fatal_error(\"FIELD_CONFIG not set in YAML.\", KeyError)\n elif fg not in api_params['FIELD_CONFIG']:\n has_fatal_error(\"{} not set in YAML.\".format(fg), KeyError)\n elif not api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"api_params['FIELD_CONFIG']['{}'] not found\".format(fg), KeyError)\n\n excluded_key = 'app_excluded_fields' if is_webapp else 'excluded_fields'\n\n if excluded_key not in api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"{}'s {} not found.\".format(fg, excluded_key))\n\n excluded_list = api_params['FIELD_CONFIG'][fg][excluded_key]\n return [get_bq_name(api_params, f, is_webapp, fg) for f in excluded_list]\n\n\ndef get_rel_prefix(bq_params):\n \"\"\"Get current release number/date (set in yaml config).\n\n :param bq_params: bq param object from yaml config\n :return: release abbreviation\n \"\"\"\n rel_prefix = ''\n\n if 'REL_PREFIX' in bq_params and bq_params['REL_PREFIX']:\n rel_prefix += bq_params['REL_PREFIX']\n if 'RELEASE' in bq_params and bq_params['RELEASE']:\n rel_prefix += bq_params['RELEASE']\n\n return rel_prefix\n\n\ndef get_fg_prefix(api_params, fg):\n \"\"\"Get field group abbreviations from yaml config, used to create field prefixes\n in order to prevent BQ column name duplication.\n\n :param api_params: api param object from yaml config\n :param fg: specific field group for which to retrieve prefix\n :return: str containing the prefix designated in yaml config for given fg\n \"\"\"\n if 'FIELD_CONFIG' not in api_params or not api_params['FIELD_CONFIG']:\n has_fatal_error('FIELD_CONFIG not in api_params, or is empty', KeyError)\n\n elif fg not in api_params['FIELD_CONFIG']:\n has_fatal_error('{} not found in not in FIELD_CONFIG'.format(fg), KeyError)\n\n elif 'prefix' not in api_params['FIELD_CONFIG'][fg]:\n has_fatal_error(\"prefix not found in FIELD_CONFIG for {}\".format(fg), KeyError)\n\n return api_params['FIELD_CONFIG'][fg]['prefix']\n\n\ndef get_table_suffixes(api_params):\n \"\"\"Get abbreviations for field groups as designated in yaml config.\n\n :param api_params: api param object from yaml config\n :return: dict of {field_group: abbreviation_suffix}\n \"\"\"\n suffixes = dict()\n\n for table, metadata in api_params['FIELD_CONFIG'].items():\n suffixes[table] = metadata['table_suffix'] if metadata['table_suffix'] else ''\n\n return suffixes\n\n\ndef build_master_table_name_from_params(bq_params):\n \"\"\"Get master table name from yaml config.\n\n :param bq_params: bq param object from yaml config\n :return: master table name\n \"\"\"\n return \"_\".join([get_rel_prefix(bq_params), bq_params['MASTER_TABLE']])\n\n\n# GETTERS - MISC\n#\n\n\n# Project and Program Getters\n\n\ndef get_program_list(bq_params):\n \"\"\"Get list of the programs which have contributed data to GDC's research program.\n\n :param bq_params: bq param object from yaml config\n :return: list of research programs participating in GDC data sharing\n \"\"\"\n programs_query = (\"\"\"\n SELECT DISTINCT(proj) \n FROM (\n SELECT SPLIT(\n (SELECT project_id\n FROM UNNEST(project)), '-')[OFFSET(0)] AS proj\n FROM `{}`)\n ORDER BY proj\n \"\"\").format(get_working_table_id(bq_params))\n\n return {prog.proj for prog in get_query_results(programs_query)}\n\n\ndef get_project_name(table_id):\n \"\"\"Get the BQ project name for a given table id.\n\n :param table_id: id in standard SQL format: '{project_id}.{dataset_id}.{table_name}'\n :return: GDC project to which the BQ table belongs\n \"\"\"\n split_table = table_id.split('.')\n\n if len(split_table) != 3:\n has_fatal_error(\"Incorrect naming for table_id: {}\".format(table_id))\n\n return split_table[0]\n\n\n# Table Getters\n\n\ndef get_one_to_many_tables(api_params, record_counts):\n \"\"\"Get one-to-many tables for program.\n\n :param api_params: api param object from yaml config\n :param record_counts: dict max field group record counts for program\n :return: set of table names (representing field groups which cannot be flattened)\n \"\"\"\n table_keys = {get_base_fg(api_params)}\n\n for table in record_counts:\n if record_counts[table] > 1:\n table_keys.add(table)\n\n return table_keys\n\n\ndef build_table_name(str_list):\n \"\"\"Constructs a table name (str) from list.\n\n :param str_list: a list of table name segments\n :return: composed table name string\n \"\"\"\n table_name = \"_\".join(str_list)\n\n # replace '.' with '_' so that the name is valid\n # ('.' chars not allowed -- issue with BEATAML1.0, for instance)\n return table_name.replace('.', '_')\n\n\ndef convert_json_to_table_name(bq_params, json_file):\n \"\"\"Convert json filename (from BQEcosystem repo) into BQ table name.\n json schema files match table ID of BQ table.\n\n :param bq_params: bq param object from yaml config\n :param json_file: json file from BQEcosystem repo containing table schema\n data and metadata; json file naming matches table ID of corresponding BQ table\n :return: BQ table name for which the json acts as a configuration file\n \"\"\"\n # handles naming for *webapp* tables\n split_name = json_file.split('.')\n program_name = split_name[1]\n split_table = split_name[2].split('_')\n table_name = '_'.join(split_table[:-2])\n rel = get_rel_prefix(bq_params)\n\n return '_'.join([rel, program_name, table_name])\n\n\ndef build_table_id(project, dataset, table):\n \"\"\" Build table_id in {project_id}.{dataset_id}.{table_name} format.\n\n :param project: project id\n :param dataset: dataset id\n :param table: table name\n :return: table_id\n \"\"\"\n return '{}.{}.{}'.format(project, dataset, table)\n\n\ndef convert_json_to_table_id(bq_params, json_file):\n \"\"\"Convert json file from BQEcosystem repo into component dataset and table names.\n Naming matches table ID of corresponding production BQ clinical tables.\n\n :param bq_params: bq param object from yaml config\n :param json_file: json file from BQEcosystem repo, storing table metadata\n :return: names of datasets and tables for production current and versioned\n repositories\n \"\"\"\n split_json = json_file.split('.')\n dest_table = \"_\".join(split_json[2].split('_')[:-1])\n\n dev_project = bq_params['DEV_PROJECT']\n prod_project = bq_params['PROD_PROJECT']\n\n dev_dataset = bq_params['DEV_DATASET']\n curr_dataset = split_json[1]\n versioned_dataset = \"_\".join([curr_dataset, bq_params['VERSIONED_SUFFIX']])\n\n src_table = \"_\".join(split_json[2].split('_')[:-2])\n src_table = \"_\".join([get_rel_prefix(bq_params), split_json[1], src_table])\n curr_table = \"_\".join([dest_table, bq_params['CURRENT_SUFFIX']])\n vers_table = \"_\".join([dest_table, get_rel_prefix(bq_params)])\n\n src_table_id = build_table_id(dev_project, dev_dataset, src_table)\n curr_table_id = build_table_id(prod_project, curr_dataset, curr_table)\n vers_table_id = build_table_id(prod_project, versioned_dataset, vers_table)\n\n return src_table_id, curr_table_id, vers_table_id\n\n\ndef get_biospecimen_table_id(bq_params, program):\n \"\"\"Builds and retrieves a table ID for the biospecimen stub tables.\n\n :param bq_params: bq param object from yaml config\n :param program: the program from which the cases originate\n :return: biospecimen table_id\n \"\"\"\n table_name = build_table_name([get_rel_prefix(bq_params),\n str(program),\n bq_params['BIOSPECIMEN_SUFFIX']])\n\n return build_table_id(bq_params['DEV_PROJECT'], bq_params['APP_DATASET'], table_name)\n\n\ndef get_working_table_id(bq_params, table_name=None):\n \"\"\"Get table id for development version of the db table.\n\n :param bq_params: bq param object from yaml config\n :param table_name: name of the bq table\n :return: table id\n \"\"\"\n if not table_name:\n table_name = build_master_table_name_from_params(bq_params)\n\n return build_table_id(bq_params[\"DEV_PROJECT\"], bq_params[\"DEV_DATASET\"], table_name)\n\n\ndef get_webapp_table_id(bq_params, table_name):\n \"\"\"Get table id for webapp db table.\n\n :param bq_params: bq param object from yaml config\n :param table_name: name of the bq table\n :return: table id\n \"\"\"\n return build_table_id(bq_params['DEV_PROJECT'], bq_params['APP_DATASET'], table_name)\n\n\n# Field and Field Group Getters\n\n\ndef get_base_fg(api_params):\n \"\"\"Get the first-level field group, of which all other field groups are descendents.\n\n :param api_params: api param object from yaml config\n :return: base field group name\n \"\"\"\n if 'FG_CONFIG' not in api_params:\n has_fatal_error(\"FG_CONFIG not set (in api_params) in YAML.\", KeyError)\n if 'base_fg' not in api_params['FG_CONFIG'] or not api_params['FG_CONFIG']['base_fg']:\n has_fatal_error(\"base_fg not set (in api_params['FG_CONFIG']) in YAML.\", KeyError)\n\n return api_params['FG_CONFIG']['base_fg']\n\n\ndef get_parent_fg(tables, field_name):\n \"\"\"\n Get field's parent table name.\n :param tables: list of table names for program\n :param field_name: full field name for which to retrieve parent table\n :return: parent table name\n \"\"\"\n parent_table = get_field_group(field_name)\n\n while parent_table and parent_table not in tables:\n parent_table = get_field_group(parent_table)\n\n if parent_table:\n return parent_table\n return has_fatal_error(\"No parent fg found for {}\".format(field_name))\n\n\ndef get_field_group(field_name):\n \"\"\"Gets parent field group (might not be the parent *table*, as the ancestor fg\n could be flattened).\n\n :param field_name: field name for which to retrieve ancestor field group\n :return: ancestor field group\n \"\"\"\n return \".\".join(field_name.split('.')[:-1])\n\n\ndef get_field_group_id_key(api_params, field_group, is_webapp=False, return_field_only=False):\n \"\"\"Retrieves the id key used to uniquely identify a table record.\n\n :param api_params: api param object from yaml config\n :param field_group: table for which to determine the id key\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: str representing table key\n \"\"\"\n\n split_fg = field_group.split('.')\n if split_fg[0] != api_params['FG_CONFIG']['base_fg']:\n split_fg.insert(0, api_params['FG_CONFIG']['base_fg'])\n field_group = \".\".join(split_fg)\n\n if field_group not in api_params['FIELD_CONFIG']:\n console_out(\"field group {} not in API_PARAMS['FIELD_CONFIG']\".format(field_group))\n return None\n if 'id_key' not in api_params['FIELD_CONFIG'][field_group]:\n has_fatal_error(\"id_key not found in API_PARAMS for {}\".format(field_group))\n\n fg_id_name = api_params['FIELD_CONFIG'][field_group]['id_key']\n\n if return_field_only:\n return fg_id_name\n\n fg_id_key = get_field_key(field_group, fg_id_name)\n\n if is_webapp:\n new_fg_id_key = get_renamed_field_key(api_params, fg_id_key)\n\n if new_fg_id_key:\n return new_fg_id_key\n\n return fg_id_key\n\n\ndef get_fg_id_name(api_params, field_group, is_webapp=False):\n \"\"\"Retrieves the id key used to uniquely identify a table record.\n\n :param api_params: api param object from yaml config\n :param field_group: table for which to determine the id key\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: str representing table key\n \"\"\"\n fg_id_key = get_field_group_id_key(api_params, field_group, is_webapp)\n\n return get_field_name(fg_id_key)\n # todo this should be replaced\n\n\ndef get_field_name(field_col_key):\n \"\"\"Get short field name from full field or bq column name.\n\n :param field_col_key: full field or bq column name\n :return: short field name\n \"\"\"\n if '.' not in field_col_key and '__' not in field_col_key:\n return field_col_key\n\n split_char = '.' if '.' in field_col_key else '__'\n\n return field_col_key.split(split_char)[-1]\n\n\ndef get_field_key(field_group, field):\n \"\"\"Get full field key (\"{field_group}.{field_name}\"}.\n\n :param field_group: field group to which the field belongs\n :param field: field name\n :return: full field key string\n \"\"\"\n return '{}.{}'.format(field_group, field)\n\n\ndef get_bq_name(api_params, field, is_webapp=False, arg_fg=None):\n \"\"\"Get column name (in bq format) from full field name.\n\n :param api_params: api params from yaml config file\n :param field: if not table_path, full field name; else short field name\n :param arg_fg: field group containing field\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: bq column name for given field name\n \"\"\"\n base_fg = get_base_fg(api_params)\n\n if arg_fg:\n # field group is specified as a function argument\n fg = arg_fg\n field_key = get_field_key(fg, field)\n elif len(field.split('.')) == 1:\n # no fg delimiter found in field string: cannot be a complete field key\n fg = base_fg\n field_key = get_field_key(fg, field)\n else:\n # no fg argument, but field contains separator chars; extract the fg and name\n fg = get_field_group(field)\n field_key = field\n\n # derive the key's short field name\n field_name = get_field_name(field_key)\n\n # get id_key and prefix associated with this fg\n this_fg_id = get_fg_id_name(api_params, fg)\n prefix = get_fg_prefix(api_params, fg)\n\n # create map of {fg_names : id_keys}\n fg_to_id_key_map = get_fgs_and_id_keys(api_params)\n\n # if fg has no prefix, or\n # field is child of base_fg, or\n # function called for webapp table building: do not add prefix\n if fg == base_fg or is_webapp or not prefix:\n return field_name\n\n # if field is an id_key, but is not mapped to this fg: do not add prefix\n if field_name in fg_to_id_key_map.values() and field_name != this_fg_id:\n return field_name\n\n # if the function reaches this line, return a prefixed field:\n # - the table is user-facing, and\n # - this field isn't a foreign id key\n return \"__\".join([prefix, field_name])\n\n\ndef get_renamed_field_key(api_params, field_key):\n \"\"\"Gets the new field name for an existing field.\n Used to rename fields for web app integration.\n\n :param api_params: api param object from yaml config\n :param field_key: field key ({fg}.{field}) for which to find a alternative field key\n :return: None if no replacement field key, otherwise string containing new field key\n \"\"\"\n if 'RENAMED_FIELDS' not in api_params:\n has_fatal_error(\"RENAMED_FIELDS not found in API_PARAMS\")\n\n renamed_fields = api_params['RENAMED_FIELDS']\n\n if not renamed_fields or (renamed_fields and field_key not in renamed_fields):\n return None\n\n return renamed_fields[field_key]\n\n\ndef get_renamed_field_keys(api_params):\n \"\"\"Get renamed fields dict from yaml config.\n\n :param api_params: api param object from yaml config\n :return: renamed fields dict\n \"\"\"\n if 'RENAMED_FIELDS' not in api_params:\n has_fatal_error(\"RENAMED_FIELDS not found in API_PARAMS\")\n\n return api_params['RENAMED_FIELDS']\n\n\n# I/O Getters\n\n\ndef build_working_gs_uri(bq_params, filename):\n \"\"\"Builds an uri reference for file uploaded to Google storage bucket.\n\n :param bq_params: bq param object from yaml config\n :param filename: file uploaded to google storage bucket\n :return: uri reference for google storage bucket file\n \"\"\"\n return \"gs://{}/{}/{}\".format(bq_params['WORKING_BUCKET'],\n bq_params['WORKING_BUCKET_DIR'],\n filename)\n\n\ndef construct_table_name(bq_params, program='', suffix='', is_webapp=False):\n \"\"\"\n todo\n :param bq_params:\n :param program:\n :param suffix:\n :param is_webapp:\n :return:\n \"\"\"\n app_prefix = bq_params['APP_JSONL_PREFIX'] if is_webapp else ''\n\n name_list = [app_prefix,\n bq_params['REL_PREFIX'] + bq_params['RELEASE'],\n program,\n bq_params['MASTER_TABLE'],\n suffix]\n\n file_name = [x for x in name_list if x]\n return '_'.join(file_name)\n\n\ndef build_jsonl_output_filename(bq_params, program='', suffix='', is_webapp=False):\n \"\"\"\n todo\n :param bq_params:\n :param program:\n :param suffix:\n :param is_webapp:\n :return:\n \"\"\"\n file_name = construct_table_name(bq_params, program, suffix, is_webapp)\n\n return file_name + '.jsonl'\n\n\ndef get_suffixed_jsonl_filename(api_params, bq_params, program, table, is_webapp=False):\n \"\"\"\n todo\n :param api_params:\n :param bq_params:\n :param program:\n :param table:\n :param is_webapp:\n :return:\n \"\"\"\n suffixes = get_table_suffixes(api_params)\n suffix = suffixes[table]\n program = program.replace('.', '_')\n\n return build_jsonl_output_filename(bq_params, program, suffix, is_webapp=is_webapp)\n\n\ndef build_jsonl_name(api_params, bq_params, program, table, is_webapp=False):\n \"\"\"\n todo\n :param api_params:\n :param bq_params:\n :param program:\n :param table:\n :param is_webapp:\n :return:\n \"\"\"\n app_prefix = bq_params['APP_JSONL_PREFIX'] if is_webapp else ''\n gdc_rel = bq_params['REL_PREFIX'] + bq_params['RELEASE']\n program = program.replace('.', '_')\n base_name = bq_params['MASTER_TABLE']\n suffix = get_table_suffixes(api_params)[table]\n\n name_list = [app_prefix, gdc_rel, program, base_name, suffix]\n filtered_name_list = [x for x in name_list if x]\n file_name = '_'.join(filtered_name_list)\n\n return file_name + '.jsonl'\n\n\ndef get_filepath(dir_path, filename=None):\n \"\"\"Get file path for location on VM.\n\n :param dir_path: directory portion of the filepath (starting at user home dir)\n :param filename: name of the file\n :return: full path to file\n \"\"\"\n join_list = [os.path.expanduser('~'), dir_path]\n\n if filename:\n join_list.append(filename)\n\n return '/'.join(join_list)\n\n\ndef get_scratch_fp(bq_params, filename):\n \"\"\"Construct filepath for VM output file.\n\n :param filename: name of the file\n :param bq_params: bq param object from yaml config\n :return: output filepath for VM\n \"\"\"\n return get_filepath(bq_params['SCRATCH_DIR'], filename)\n\n\n# FILESYSTEM HELPERS\n\n\ndef get_dir(fp):\n \"\"\" Get directory component of filepath.\n\n :param fp: full filepath (dir and file name)\n :return: directory component of fp\n \"\"\"\n return '/'.join(fp.split('/')[:-1])\n\n\ndef write_list_to_jsonl(jsonl_fp, json_obj_list, mode='w'):\n \"\"\" Create a jsonl file for uploading data into BQ from a list obj.\n\n :param jsonl_fp: filepath of jsonl file to write\n :param json_obj_list: list object\n :param mode: 'a' if appending to a file that's being built iteratively\n 'w' if file data is written in a single call to the function\n (in which case any existing data is overwritten)\"\"\"\n\n with open(jsonl_fp, mode) as file_obj:\n cnt = 0\n\n for line in json_obj_list:\n json.dump(obj=line, fp=file_obj)\n file_obj.write('\\n')\n cnt += 1\n\n\ndef append_list_to_jsonl(file_obj, json_list):\n try:\n for line in json_list:\n json_str = convert_dict_to_string(line)\n json.dump(obj=json_str, fp=file_obj)\n file_obj.write('\\n')\n except IOError as err:\n print(str(err), IOError)\n\n\ndef delete_file(fp):\n if os.path.exists(fp):\n os.remove(fp)\n print(\"{} deleted successfully!\".format(fp))\n else:\n print(\"{} not found!\".format(fp))\n\n\n# REST API HELPERS (GDC, PDC, ETC)\n\n\ndef create_mapping_dict(endpoint):\n \"\"\"Creates a dict containing field mappings for given endpoint.\n Note: only differentiates the GDC API's 'long' type (called 'integer' in GDC data\n dictionary) and 'float' type (called 'number' in GDC data dictionary). All others\n typed as string.\n\n :param endpoint: API endpoint for which to retrieve mapping\n :return: dict of field maps. Each entry contains field name, type, and description\n \"\"\"\n field_mapping_dict = {}\n\n # retrieve mappings json object\n res = requests.get(endpoint + '/_mapping')\n field_mappings = res.json()['_mapping']\n\n for field in field_mappings:\n # convert data types from GDC format to formats used in BQ\n if field_mappings[field]['type'] == 'long':\n field_type = 'INTEGER'\n elif field_mappings[field]['type'] == 'float':\n field_type = 'FLOAT'\n else:\n field_type = 'STRING'\n\n # create json object of field mapping data\n field_mapping_dict[field] = {\n 'name': field.split('.')[-1],\n 'type': field_type,\n 'description': field_mappings[field]['description']\n }\n\n return field_mapping_dict\n\n\ndef create_schema_dict(api_params, bq_params, is_webapp=False):\n \"\"\"Creates schema dict using master table's bigquery.table.Table.schema attribute.\n\n :param api_params: api param object from yaml config\n :param bq_params: bq params from yaml config file\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n :return: flattened schema dict in format:\n {full field name: {name: 'name', type: 'field_type', description: 'description'}}\n \"\"\"\n client = bigquery.Client()\n bq_table = client.get_table(get_working_table_id(bq_params))\n\n schema_list = []\n\n for schema_field in bq_table.schema:\n schema_list.append(schema_field.to_api_repr())\n\n schema = dict()\n\n parse_bq_schema_obj(api_params=api_params,\n schema=schema,\n fg=get_base_fg(api_params),\n schema_list=schema_list,\n is_webapp=is_webapp)\n\n return schema\n\n\ndef get_cases_by_program(bq_params, program):\n \"\"\"Get a dict obj containing all the cases associated with a given program.\n\n :param bq_params: bq param object from yaml config\n :param program: the program from which the cases originate\n :return: cases dict\n \"\"\"\n start_time = time.time()\n cases = []\n\n sample_table_id = get_biospecimen_table_id(bq_params, program)\n\n query = \"\"\"\n SELECT * \n FROM `{}` \n WHERE case_id IN (\n SELECT DISTINCT(case_gdc_id) \n FROM `{}`\n WHERE project_name = '{}')\n \"\"\".format(get_working_table_id(bq_params), sample_table_id, program)\n\n for case_row in get_query_results(query):\n case_items = dict(case_row.items())\n case_items.pop('project')\n cases.append(case_items)\n\n end_time = time.time() - start_time\n\n return cases\n\n\ndef get_graphql_api_response(api_params, query, fail_on_error=True):\n max_retries = 4\n\n headers = {'Content-Type': 'application/json'}\n endpoint = api_params['ENDPOINT']\n\n if not query:\n has_fatal_error(\"Must specify query for get_graphql_api_response.\", SyntaxError)\n\n req_body = {'query': query}\n api_res = requests.post(endpoint, headers=headers, json=req_body)\n tries = 0\n\n while not api_res.ok and tries < max_retries:\n console_out(\"API response status code {}: {};\\nRetry {} of {}...\",\n (api_res.status_code, api_res.reason, tries, max_retries))\n time.sleep(3)\n\n api_res = requests.post(endpoint, headers=headers, json=req_body)\n\n tries += 1\n\n if tries > max_retries:\n # give up!\n api_res.raise_for_status()\n\n json_res = api_res.json()\n\n if 'errors' in json_res and json_res['errors']:\n if fail_on_error:\n has_fatal_error(\"Errors returned by {}.\\nError json:\\n{}\".format(endpoint, json_res['errors']))\n return None\n\n return json_res\n\n\n# BIGQUERY API HELPERS\n\n\ndef get_last_fields_in_table(api_params):\n \"\"\" Get list of fields to always include at the end of merged tables,\n via the yaml config.\n\n :param api_params: api param object from yaml config\n :return: fields to include at the end of the table\n \"\"\"\n if 'FG_CONFIG' not in api_params:\n has_fatal_error(\"Missing FG_CONFIG in YAML\", KeyError)\n elif 'last_keys_in_table' not in api_params['FG_CONFIG']:\n has_fatal_error(\"Missing last_keys_in_table in FG_CONFIG in YAML\", KeyError)\n\n return api_params['FG_CONFIG']['last_keys_in_table']\n\n\ndef parse_bq_schema_obj(api_params, schema, fg, schema_list=None, is_webapp=False):\n \"\"\"Recursively construct schema using existing metadata in main clinical table.\n\n :param api_params: api param object from yaml config\n :param schema: dict of flattened schema entries\n :param fg: current field group name\n :param schema_list: schema field entries for field_group\n :param is_webapp: is script currently running the 'create_webapp_tables' step?\n \"\"\"\n\n if fg not in api_params['FIELD_CONFIG']:\n return\n\n for i, schema_field in enumerate(schema_list):\n\n field_key = get_field_key(fg, schema_field['name'])\n\n # if has 'fields', then the current obj contains nested objs\n if schema_field['type'] == 'RECORD':\n # if nested, recurse down to the next level\n parse_bq_schema_obj(api_params, schema, field_key, schema_field['fields'], is_webapp)\n\n required_field_list = get_required_fields(api_params, fg)\n\n for field_name in required_field_list:\n schema[field_name]['mode'] = 'REQUIRED'\n else:\n # not a nested field entry--do we need to prefix the schema field name?\n schema_field['name'] = get_bq_name(api_params, field_key, is_webapp)\n schema[field_key] = schema_field\n\n\ndef get_fgs_and_id_keys(api_params):\n \"\"\" Create a dictionary of type { 'field_group' : 'id_key_field'}.\n\n :param api_params: api param object from yaml config\n :return: mapping dict, field group -> id_key_field\n \"\"\"\n id_key_dict = dict()\n\n fg_config_entries = api_params['FIELD_CONFIG']\n\n for fg in fg_config_entries:\n id_key_dict[fg] = fg_config_entries[fg]['id_key']\n\n return id_key_dict\n\n\ndef copy_bq_table(bq_params, src_table, dest_table, replace_table=False):\n \"\"\"Copy an existing BQ table into a new location.\n\n :param bq_params: bq param object from yaml config\n :param src_table: Table to copy\n :param dest_table: Table to be created\n \"\"\"\n client = bigquery.Client()\n\n job_config = bigquery.CopyJobConfig()\n\n if replace_table:\n delete_bq_table(dest_table)\n\n bq_job = client.copy_table(src_table, dest_table, job_config=job_config)\n\n if await_job(bq_params, client, bq_job):\n console_out(\"Successfully copied table:\")\n console_out(\"src: {0}\\n dest: {1}\\n\", (src_table, dest_table))\n\n\ndef create_and_load_table(bq_params, jsonl_file, schema, table_id):\n \"\"\"Creates BQ table and inserts case data from jsonl file.\n\n :param bq_params: bq param obj from yaml config\n :param jsonl_file: file containing case records in jsonl format\n :param schema: list of SchemaFields representing desired BQ table schema\n :param table_id: id of table to create\n \"\"\"\n client = bigquery.Client()\n job_config = bigquery.LoadJobConfig()\n job_config.schema = schema\n job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON\n job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE\n\n gs_uri = build_working_gs_uri(bq_params, jsonl_file)\n\n try:\n load_job = client.load_table_from_uri(gs_uri, table_id, job_config=job_config)\n console_out(' - Inserting into {0}... ', (table_id,), end=\"\")\n await_insert_job(bq_params, client, table_id, load_job)\n except TypeError as err:\n has_fatal_error(err)\n\n\ndef create_and_load_tsv_table(bq_params, tsv_file, schema, table_id, null_marker=''):\n \"\"\"Creates BQ table and inserts case data from jsonl file.\n\n :param bq_params: bq param obj from yaml config\n :param tsv_file: file containing case records in tsv format\n :param schema: list of SchemaFields representing desired BQ table schema\n :param table_id: id of table to create\n \"\"\"\n client = bigquery.Client()\n job_config = bigquery.LoadJobConfig()\n job_config.schema = schema\n job_config.source_format = bigquery.SourceFormat.CSV\n job_config.field_delimiter = '\\t'\n job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE\n job_config.skip_leading_rows = 1\n job_config.null_marker = null_marker # todo added this back, is that ok?\n\n gs_uri = build_working_gs_uri(bq_params, tsv_file)\n\n try:\n load_job = client.load_table_from_uri(gs_uri, table_id, job_config=job_config)\n\n console_out(' - Inserting into {0}... ', (table_id,), end=\"\")\n await_insert_job(bq_params, client, table_id, load_job)\n except TypeError as err:\n has_fatal_error(err)\n\n\ndef delete_bq_table(table_id):\n \"\"\"Permanently delete BQ table located by table_id.\n\n :param table_id: table id in standard SQL format\n \"\"\"\n client = bigquery.Client()\n client.delete_table(table_id, not_found_ok=True)\n\n console_out(\"deleted table: {0}\", (table_id,))\n\n\ndef exists_bq_table(table_id):\n \"\"\"Determine whether bq_table exists.\n\n :param table_id: table id in standard SQL format\n :return: True if exists, False otherwise\n \"\"\"\n client = bigquery.Client()\n\n try:\n client.get_table(table_id)\n except NotFound:\n return False\n return True\n\n\ndef load_table_from_query(bq_params, table_id, query):\n \"\"\"Create a new BQ table from the returned results of querying an existing BQ db.\n\n :param bq_params: bq params from yaml config file\n :param table_id: table id in standard SQL format\n :param query: query which returns data to populate a new BQ table.\n \"\"\"\n client = bigquery.Client()\n job_config = bigquery.QueryJobConfig(destination=table_id)\n job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE\n\n try:\n query_job = client.query(query, job_config=job_config)\n console_out(' - Inserting into {0}... ', (table_id,), end=\"\")\n await_insert_job(bq_params, client, table_id, query_job)\n except TypeError as err:\n has_fatal_error(err)\n\n\ndef get_bq_table_obj(table_id):\n \"\"\"Get the bq table referenced by table_id.\n\n :param table_id: table id in standard SQL format\n :return: bq Table object\n \"\"\"\n if not exists_bq_table(table_id):\n return None\n\n client = bigquery.Client()\n return client.get_table(table_id)\n\n\ndef get_query_results(query):\n \"\"\"Returns BigQuery query result object.\n\n :param query: query string\n :return: result object\n \"\"\"\n client = bigquery.Client()\n query_job = client.query(query)\n return query_job.result()\n\n\ndef await_insert_job(bq_params, client, table_id, bq_job):\n \"\"\"Monitor the completion of BQ Job which does produce some result\n (usually data insertion).\n\n :param bq_params: bq params from yaml config file\n :param client: BQ api object, allowing for execution of bq lib functions\n :param table_id: table id in standard SQL format\n :param bq_job: A Job object, responsible for executing bq function calls\n \"\"\"\n last_report_time = time.time()\n location = bq_params['LOCATION']\n job_state = \"NOT_STARTED\"\n\n while job_state != 'DONE':\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n if time.time() - last_report_time > 30:\n console_out('\\tcurrent job state: {0}...\\t', (bq_job.state,), end='')\n last_report_time = time.time()\n\n job_state = bq_job.state\n\n if job_state != 'DONE':\n time.sleep(2)\n\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n if bq_job.error_result is not None:\n has_fatal_error(\n 'While running BQ job: {}\\n{}'.format(bq_job.error_result, bq_job.errors),\n ValueError)\n\n table = client.get_table(table_id)\n console_out(\" done. {0} rows inserted.\", (table.num_rows,))\n\n\ndef await_job(bq_params, client, bq_job):\n \"\"\"Monitor the completion of BQ Job which doesn't return a result.\n\n :param bq_params: bq params from yaml config file\n :param client: BQ api object, allowing for execution of bq lib functions\n :param bq_job: A Job object, responsible for executing bq function calls\n \"\"\"\n location = bq_params['LOCATION']\n job_state = \"NOT_STARTED\"\n\n while job_state != 'DONE':\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n job_state = bq_job.state\n\n if job_state != 'DONE':\n time.sleep(2)\n\n bq_job = client.get_job(bq_job.job_id, location=location)\n\n if bq_job.error_result is not None:\n err_res = bq_job.error_result\n errs = bq_job.errors\n has_fatal_error(\"While running BQ job: {}\\n{}\".format(err_res, errs))\n\n\ndef from_schema_file_to_obj(bq_params, filename):\n \"\"\"\n Open table schema file and convert to python dict, in order to pass the data to\n BigQuery for table insertion.\n\n :param bq_params: bq param object from yaml config\n :param filename: name of the schema file\n :return: schema list, table metadata dict\n \"\"\"\n\n fp = get_filepath(bq_params['SCHEMA_DIR'], filename)\n # todo changed this, does it work?\n\n if not os.path.exists(fp):\n return None, None\n\n with open(fp, 'r') as schema_file:\n try:\n schema_file = json.load(schema_file)\n\n schema = schema_file['schema']['fields']\n\n table_metadata = {\n 'description': schema_file['description'],\n 'friendlyName': schema_file['friendlyName'],\n 'labels': schema_file['labels']\n }\n except FileNotFoundError:\n return None, None\n\n return schema, table_metadata\n\n\ndef to_bq_schema_obj(schema_field_dict):\n \"\"\"Convert schema entry dict to SchemaField object.\n\n :param schema_field_dict: dict containing schema field keys\n (name, field_type, mode, fields, description)\n :return: bigquery.SchemaField object\n \"\"\"\n return bigquery.SchemaField.from_api_repr(schema_field_dict)\n\n\ndef generate_bq_schema(schema_dict, record_type, expand_fields_list):\n \"\"\"Generates BigQuery SchemaField list for insertion of case records.\n\n :param schema_dict: dict of schema fields\n :param record_type: type of field/field group\n :param expand_fields_list: list of field groups included in API request\n :return: list of SchemaFields for case record insertion\n \"\"\"\n # add fields to a list in order to generate a dict representing nested fields\n field_group_names = [record_type]\n nested_depth = 0\n\n for field_group in expand_fields_list.split(','):\n nested_field_name = record_type + '.' + field_group\n nested_depth = max(nested_depth, len(nested_field_name.split('.')))\n field_group_names.append(nested_field_name)\n\n record_lists_dict = {field_grp_name: [] for field_grp_name in field_group_names}\n # add field to correct field grouping list based on full field name\n for field in schema_dict:\n # record_lists_dict key is equal to the parent field components of\n # full field name\n record_lists_dict[get_field_group(field)].append(schema_dict[field])\n\n temp_schema_field_dict = {}\n\n while nested_depth >= 1:\n for field_group_name in record_lists_dict:\n split_group_name = field_group_name.split('.')\n\n # builds from max depth inward to avoid iterating through entire schema obj\n # in order to append child field groups. Skip any shallower field groups.\n if len(split_group_name) != nested_depth:\n continue\n\n schema_field_sublist = []\n\n for record in record_lists_dict[field_group_name]:\n schema_field_sublist.append(\n bigquery.SchemaField(name=record['name'],\n field_type=record['type'],\n mode='NULLABLE',\n description=record['description'],\n fields=()))\n\n parent_name = get_field_group(field_group_name)\n\n if field_group_name in temp_schema_field_dict:\n schema_field_sublist += temp_schema_field_dict[field_group_name]\n\n if parent_name:\n if parent_name not in temp_schema_field_dict:\n temp_schema_field_dict[parent_name] = list()\n\n temp_schema_field_dict[parent_name].append(\n bigquery.SchemaField(name=get_field_name(field_group_name),\n field_type='RECORD',\n mode='REPEATED',\n description='',\n fields=tuple(schema_field_sublist)))\n else:\n if nested_depth > 1:\n has_fatal_error(\"Empty parent_name at level {}\"\n .format(nested_depth), ValueError)\n return schema_field_sublist\n\n nested_depth -= 1\n return None\n\n\ndef update_table_metadata(table_id, metadata):\n \"\"\"Modify an existing BQ table with additional metadata.\n\n :param table_id: table id in standard SQL format\n :param metadata: metadata containing new field and table attributes\n \"\"\"\n client = bigquery.Client()\n table = get_bq_table_obj(table_id)\n\n table.labels = metadata['labels']\n table.friendly_name = metadata['friendlyName']\n table.description = metadata['description']\n client.update_table(table, [\"labels\", \"friendly_name\", \"description\"])\n\n assert table.labels == metadata['labels']\n assert table.friendly_name == metadata['friendlyName']\n assert table.description == metadata['description']\n\n\ndef update_friendly_name(bq_params, table_id, custom_name=None):\n \"\"\"Modify a table's friendly name metadata.\n\n :param bq_params: bq param object from yaml config\n :param table_id: table id in standard SQL format\n :param custom_name: By default, appends \"'REL' + bq_params['RELEASE'] + ' VERSIONED'\"\n onto the existing friendly name. If custom_name is specified, this behavior is\n overridden, and the table's friendly name is replaced entirely.\n \"\"\"\n client = bigquery.Client()\n table = get_bq_table_obj(table_id)\n\n if custom_name:\n new_name = custom_name\n else:\n new_name = table.friendly_name + ' REL' + bq_params['RELEASE'] + ' VERSIONED'\n\n table.friendly_name = new_name\n client.update_table(table, [\"friendly_name\"])\n\n assert table.friendly_name == new_name\n\n\ndef update_schema(table_id, new_descriptions):\n \"\"\"Modify an existing table's field descriptions.\n\n :param table_id: table id in standard SQL format\n :param new_descriptions: dict of field names and new description strings\n \"\"\"\n client = bigquery.Client()\n table = get_bq_table_obj(table_id)\n\n new_schema = []\n\n for schema_field in table.schema:\n field = schema_field.to_api_repr()\n\n if field['name'] in new_descriptions.keys():\n name = field['name']\n field['description'] = new_descriptions[name]\n elif field['description'] == '':\n console_out(\"Still no description for field: {0}\", (field['name']))\n\n mod_field = bigquery.SchemaField.from_api_repr(field)\n new_schema.append(mod_field)\n\n table.schema = new_schema\n\n client.update_table(table, ['schema'])\n\n\n# (NON-BQ) GOOGLE CLOUD API HELPERS\n\n\ndef upload_file_to_bucket(project, bucket, blob_dir, fp):\n \"\"\"\n todo\n :param project:\n :param bucket:\n :param blob_dir:\n :param fp:\n :return:\n \"\"\"\n try:\n client = storage.Client(project=project)\n bucket = client.get_bucket(bucket)\n blob = bucket.blob(blob_dir)\n\n blob.upload_from_file(fp)\n except exceptions.GoogleCloudError as err:\n has_fatal_error(\"Failed to upload to bucket.\\n{}\".format(err))\n\n\ndef upload_to_bucket(bq_params, scratch_fp):\n \"\"\"Uploads file to a google storage bucket (location specified in yaml config).\n\n :param bq_params: bq param object from yaml config\n :param scratch_fp: name of file to upload to bucket\n \"\"\"\n\n try:\n storage_client = storage.Client(project=\"\")\n\n jsonl_output_file = scratch_fp.split('/')[-1]\n blob_name = \"{}/{}\".format(bq_params['WORKING_BUCKET_DIR'], jsonl_output_file)\n bucket = storage_client.bucket(bq_params['WORKING_BUCKET'])\n blob = bucket.blob(blob_name)\n\n blob.upload_from_filename(scratch_fp)\n except exceptions.GoogleCloudError as err:\n has_fatal_error(\"Failed to upload to bucket.\\n{}\".format(err))\n\n\ndef download_from_bucket(bq_params, filename):\n storage_client = storage.Client(project=\"\")\n blob_name = \"{}/{}\".format(bq_params['WORKING_BUCKET_DIR'], filename)\n bucket = storage_client.bucket(bq_params['WORKING_BUCKET'])\n blob = bucket.blob(blob_name)\n\n scratch_fp = get_scratch_fp(bq_params, filename)\n with open(scratch_fp, 'wb') as file_obj:\n blob.download_to_file(file_obj)\n\n\n# ANALYZE DATA\n\n\ndef check_value_type(value):\n \"\"\"Checks value for type (possibilities are string, float and integers).\n\n :param value: value to type check\n :return: type in BQ column format\n \"\"\"\n # if has leading zero, then should be considered a string, even if only\n # composed of digits\n val_is_none = value in ('NA', 'null', 'None') or not value\n val_is_bool = value in ('True', 'False', True, False)\n val_is_decimal = value.startswith('0.')\n val_is_id = value.startswith('0') and not val_is_decimal and len(value) > 1\n\n try:\n float(value)\n val_is_num = True\n # Changing this because google won't accept loss of precision in the\n # data insert job\n # (won't cast 1.0 as 1)\n val_is_float = not value.isdigit()\n # If this is used, a field with only trivial floats will be cast as\n # Integer. However, BQ errors due to loss\n # of precision.\n # val_is_float = True if int(float(value)) != float(value) else False\n except ValueError:\n val_is_num = False\n val_is_float = False\n\n if val_is_none:\n return None\n if val_is_id:\n return 'STRING'\n if val_is_decimal or val_is_float:\n return 'FLOAT'\n if val_is_num:\n return 'INTEGER'\n if val_is_bool:\n return 'BOOLEAN'\n\n return 'STRING'\n\n\ndef collect_values(fields, field, parent, field_grp_prefix):\n \"\"\"Recursively inserts sets of values for a given field into return dict (\n used to infer field data type).\n\n :param fields: A dict of key:value pairs -- {field_name: set(field_values)}\n :param field: field name\n :param parent: dict containing field and it's values\n :param field_grp_prefix: string representation of current location in field hierarchy\n :return: field_dict containing field names and a set of its values\n \"\"\"\n # If the value of parent_dict[key] is a list at this level, and a dict at the next\n # (or a dict at this level, as seen in second conditional statement),\n # iterate over each list element's dictionary entries. (Sometimes lists are composed\n # of strings rather than dicts, and those are later converted to strings.)\n field_name = field_grp_prefix + field\n new_prefix = field_name + '.'\n\n if isinstance(parent[field], list) \\\n and len(parent[field]) > 0 and isinstance(parent[field][0], dict):\n for dict_item in parent[field]:\n for dict_key in dict_item:\n fields = collect_values(fields, dict_key, dict_item, new_prefix)\n elif isinstance(parent[field], dict):\n for dict_key in parent[field]:\n fields = collect_values(fields, dict_key, parent[field], new_prefix)\n else:\n if field_name not in fields:\n fields[field_name] = set()\n\n # This type of list can be converted to a comma-separated value string\n if isinstance(parent[field], list):\n value = \", \".join(parent[field])\n else:\n value = parent[field]\n\n fields[field_name].add(value)\n\n return fields\n\n\ndef infer_data_types(flattened_json):\n \"\"\"Infer data type of fields based on values contained in dataset.\n\n :param flattened_json: file containing dict of {field name: set of field values}\n :return: dict of field names and inferred type (None if no data in value set)\n \"\"\"\n data_types = dict()\n\n for column in flattened_json:\n data_types[column] = None\n\n for value in flattened_json[column]:\n if data_types[column] == 'STRING':\n break\n\n # adding this change because organoid submitter_ids look like\n # ints, but they should be str for uniformity\n if column[-2:] == 'id':\n data_types[column] = 'STRING'\n break\n\n val_type = check_value_type(str(value))\n\n if not val_type:\n continue\n if val_type in ('FLOAT', 'STRING') or (\n val_type in ('INTEGER', 'BOOLEAN') and not data_types[column]):\n data_types[column] = val_type\n\n return data_types\n\n\ndef get_sorted_fg_depths(record_counts, reverse=False):\n \"\"\"Returns a sorted dict of field groups: depths.\n\n :param record_counts: dict containing field groups and associated record counts\n :param reverse: if True, sort in DESC order, otherwise sort in ASC order\n :return: tuples composed of field group names and record counts\n \"\"\"\n table_depths = {table: len(table.split('.')) for table in record_counts}\n\n return sorted(table_depths.items(), key=lambda item: item[1], reverse=reverse)\n\n\n# MISC UTILITIES\n\n\ndef format_seconds(seconds):\n if seconds > 3600:\n return time.strftime(\"%-H hours, %-M minutes, %-S seconds\", time.gmtime(seconds))\n if seconds > 60:\n return time.strftime(\"%-M minutes, %-S seconds\", time.gmtime(seconds))\n\n return time.strftime(\"%-S seconds\", time.gmtime(seconds))\n\n\ndef convert_dict_to_string(obj):\n \"\"\"Converts dict/list of primitives or strings to a comma-separated string. Used\n to write data to file.\n\n :param obj: object to converts\n :return: modified object\n \"\"\"\n if isinstance(obj, list):\n if not isinstance(obj[0], dict):\n str_list = ', '.join(obj)\n obj = str_list\n else:\n for idx, value in enumerate(obj.copy()):\n obj[idx] = convert_dict_to_string(value)\n elif isinstance(obj, dict):\n for key in obj:\n obj[key] = convert_dict_to_string(obj[key])\n return obj\n\n\ndef load_config(args, yaml_dict_keys):\n \"\"\"Opens yaml file and retrieves configuration parameters.\n\n :param args: args param from python bash cli\n :param yaml_dict_keys: tuple of strings representing a subset of the yaml file's\n top-level dict keys\n :return: tuple of dicts from yaml file (as requested in yaml_dict_keys)\n \"\"\"\n if len(args) != 2:\n has_fatal_error('Usage: {} \".format(args[0])', ValueError)\n\n yaml_file_arg = args[1]\n\n with open(yaml_file_arg, mode='r') as yaml_file_arg:\n\n yaml_dict = None\n\n config_stream = io.StringIO(yaml_file_arg.read())\n\n try:\n yaml_dict = yaml.load(config_stream, Loader=yaml.FullLoader)\n except yaml.YAMLError as ex:\n has_fatal_error(ex, str(yaml.YAMLError))\n if yaml_dict is None:\n has_fatal_error(\"Bad YAML load, exiting.\", ValueError)\n\n # Dynamically generate a list of dictionaries for the return statement,\n # since tuples are immutable\n return_dicts = [yaml_dict[key] for key in yaml_dict_keys]\n\n return tuple(return_dicts)\n\n\ndef has_fatal_error(err, exception=None):\n \"\"\"Error handling function--outputs error str or list;\n optionally throws Exception as well.\n\n :param err: error message str or list\n :param exception: Exception type for error (defaults to None)\n \"\"\"\n err_str_prefix = '[ERROR] '\n err_str = ''\n\n if isinstance(err, list):\n for item in err:\n err_str += err_str_prefix + str(item) + '\\n'\n else:\n err_str = err_str_prefix + err\n\n console_out(err_str)\n\n if exception:\n raise exception\n\n sys.exit(1)\n\n\ndef console_out(output_str, print_vars=None, end='\\n'):\n \"\"\"\n todo\n :param output_str:\n :param print_vars:\n :param end:\n :return:\n \"\"\"\n if print_vars:\n print(str(output_str).format(*print_vars), end=end)\n else:\n print(output_str, end=end)\n\n\ndef modify_fields_for_app(api_params, schema, column_order_dict, columns):\n \"\"\"Alter field naming conventions so that they're compatible with those in the\n web app.\n\n :param api_params: api param object from yaml config\n :param schema: dict containing schema records\n :param column_order_dict: dict of {field_groups: column_order set()}\n :param columns: dict containing table column keys\n \"\"\"\n renamed_fields = dict(api_params['RENAMED_FIELDS'])\n fgs = column_order_dict.keys()\n\n excluded_fgs = get_excluded_field_groups(api_params)\n excluded_fields = get_excluded_fields_all_fgs(api_params, fgs, is_webapp=True)\n\n for fg in fgs:\n # rename case_id no matter which fg it's in\n for renamed_field in renamed_fields.keys():\n if renamed_field in column_order_dict[fg]:\n new_field = renamed_fields[renamed_field]\n column_order_dict[fg][new_field] = column_order_dict[fg][renamed_field]\n column_order_dict[fg].pop(renamed_field)\n if fg in columns and renamed_field in columns[fg]:\n columns[fg].add(renamed_fields[renamed_field])\n columns[fg].remove(renamed_field)\n\n # field is fully associated name\n for field in {k for k in schema.keys()}:\n base_fg = \".\".join(field.split('.')[:-1])\n field_name = field.split('.')[-1]\n\n # substitute base field name for prefixed\n schema[field]['name'] = field_name\n\n # exclude any field groups or fields explicitly excluded in yaml\n if field in excluded_fields or base_fg in excluded_fgs:\n schema.pop(field)\n # field exists in renamed_fields, change its name\n elif field in renamed_fields:\n new_field = renamed_fields[field]\n\n schema[field]['name'] = new_field.split('.')[-1]\n schema[new_field] = schema[field]\n schema.pop(field)\n\n # change the field name in the column order dict\n if base_fg in column_order_dict and field in column_order_dict[base_fg]:\n column_order_dict[base_fg][new_field] = column_order_dict[base_fg][field]\n column_order_dict[base_fg].pop(field)\n\n if field in excluded_fields and base_fg in column_order_dict:\n # remove excluded field from column order lists\n if field in column_order_dict[base_fg]:\n column_order_dict[base_fg].pop(field)\n\n\ndef create_tsv_row(row_list, null_marker=\"None\"):\n print_str = ''\n last_idx = len(row_list) - 1\n\n for i, column in enumerate(row_list):\n if not column:\n column = null_marker\n\n delimiter = \"\\t\" if i < last_idx else \"\\n\"\n print_str += column + delimiter\n\n return print_str\n","sub_path":"common_etl/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":57502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"324269613","text":"# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, include, url\n\nfrom . import views\nfrom django.views.decorators.csrf import csrf_exempt\n\nurlpatterns = patterns('',\n url('^initiatives/(?P\\d+)/$', views.InitiativeDetailView.as_view(),\n name='initiative_detail'),\n\n url('^initiatives/(?P\\d+)/edit/$', views.InitiativeEditView.as_view(),\n name='initiative_edit'),\n\n url('^api/v1/municipalities$', views.MunicipalityListApiView.as_view(),\n name='municipalities_list'),\n\n url('^services/nua/1.0/create$', csrf_exempt(views.CreateInitivateApiView.as_view()),\n name='create_initiative')\n)","sub_path":"kuaapi/simulation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"140719470","text":"import PresetModel\nfrom tkinter import messagebox\nimport tkinter\nimport os\nimport InventorySlot\nimport UserWarnings\n\nclass PresetHandler:\n def __init__(self):\n self.targetModel = PresetModel.PresetModel()\n self.model = None\n self.f = None\n self.basicData = dict()\n \"\"\"self.filename = \"default.preset\"\n self.filepath = \".\"\n self.defaultKey = True\n self.key = 'q'\n self.afkmessage = \"afk\"\n self.inventoryData = dict()\"\"\"\n\n def __str__(self):\n return str(self.inventoryData)\n\n def loadFile(self, filepath, filename, combined=False):\n try: \n if combined:\n constr = filepath\n tmp = filepath.split(\"/\")\n self.filename = tmp[-1]\n '/'.join(tmp[:-1])\n else:\n self.filename = filename\n self.filepath = filepath\n constr = self.filepath + \"/\" + self.filename\n for line in open(constr):\n sep = line.split(' ')\n if sep[0][-1]!=':':\n print(\"[E] Fehler beim Laden der Vorlagenzeile:\", line)\n raise ValueError\n firstWord = sep[0][:-1]\n if firstWord==\"data\":\n slot = self.readInventoryLine(sep)\n self.targetModel.addSlot(slot)\n else:\n rest = ' '.join(sep[1:])\n if rest[-1]=='\\n':\n self.basicData[firstWord] = rest[:-1]\n else:\n self.basicData[firstWord] = rest\n\n print(self.basicData)\n\n for ele in self.basicData:\n self.targetModel.set(ele, self.basicData[ele])\n\n return self.targetModel\n except:\n UserWarnings.showBrokenPresetError()\n return \"Error occurred\"\n\n\n def readInventoryLine(self, lineToRead):\n #Error Handling muss in Aufruffunktion gemacht werden!\n #data: 1 32 500 bea con\n #data: slot Anzahl Preis Material\n #lineToRead = ['data:', '1', '32', '500', 'bea', con']\n newSlot = InventorySlot.InventorySlot()\n newSlot.setPosition(int(lineToRead[1]))\n newSlot.setCount(int(lineToRead[2]))\n newSlot.setPrice(int(lineToRead[3]))\n newSlot.setItem(' '.join(lineToRead[4:]))\n return newSlot\n\n\n def get(self, what):\n pass\n \"\"\"if self.data[what]==None:\n print(\"[E] Angeforderten Datenwert in der aktuellen Config nicht gefunden:\", what)\n return\n return self.data[what]\"\"\"\n\n def setModel(self, model):\n self.model = model\n\n def deleteFile(self, model):\n strin = model.get(\"filepath\") + \"/\" + model.get(\"filename\")\n os.remove(strin)\n\n def saveToFile(self, model=None):\n if model != None:\n self.model = model\n print(self.model)\n \n composed = self.model.get(\"filepath\") + \"/\" + self.model.get(\"filename\")\n self.f = open(composed, \"w+\")\n for element in self.model.data:\n appen = str(element) + \": \" + str(self.model.get(element)) + \"\\n\"\n self.f.write(appen)\n for slott in self.model.getASlotlist():\n if slott != None:\n appen = \"data: \" + str(slott.getPosition()) + \" \" + str(slott.getCount()) + \" \" + str(slott.getPrice()) + \" \" + str(slott.getItem())\n self.f.write(appen)\n self.f.close()","sub_path":"release/GrieferBOT2_01/PresetHandler.py","file_name":"PresetHandler.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"271528252","text":"#coding:utf8\n\nfrom flask import Flask\nfrom functions import loadClass\napp=Flask(__name__)\n\n@app.route('////',\n methods=['GET','POST','PUT','DELETE'])\ndef index(version,method,controller):\n getClass=loadClass(version, controller)\n do=getattr(getClass(),'do') \n return do()\n\n@app.after_request\ndef add_headers(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n return response\n\n\napp.run(\"10.10.10.13\", 9090, debug=True)\n\n","sub_path":"api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"401764032","text":"from django.shortcuts import render, get_object_or_404\n\nfrom .models import Post, Categoria\n\n\ndef lista_posts(request):\n # Ordenar los post por fecha descendentemente order_by('')\n posts = Post.objects.all().order_by('-fecha')\n # Tambien devolver los post destacados en otra variable\n posts_destacados = Post.objects.filter(destacado=True)\n # Tambien devolver las categorias\n categorias = Categoria.objects.all()\n return render(request, 'blog/lista_posts.html',\n {'posts': posts,\n 'posts_destacados': posts_destacados,\n 'categorias': categorias})\n\n\ndef detalle_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n return render(request, 'blog/detalle_post.html',\n {'post': post})\n\n\ndef posts_categoria(request, pk):\n categoria = get_object_or_404(Categoria, pk=pk)\n posts = Post.objects.filter(categoria=categoria).order_by('-fecha')\n posts_destacados = Post.objects.filter(destacado=True)\n categorias = Categoria.objects.all()\n return render(request, 'blog/lista_posts.html',\n {'posts': posts,\n 'posts_destacados': posts_destacados,\n 'categorias': categorias})\n","sub_path":"devdiary/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"99489052","text":"print('api包的init文件')\r\n__all__=['x','y','policy','versions']\r\nfrom . import policy\r\nx=1\r\ny=2\r\n# policy=123123123123\r\n# versions='123123123'\r\n\r\n\r\n#import policy#以test.py的sys.path为准,不能在包内导入自己的模块\r\n\r\n#绝对导入\r\n#from glance.api import policy\r\n# from glance.api import versions\r\n\r\n#相对导入\r\n#\r\n# from . import policy,versions #推荐\r\n#\r\n#from ..cmd.manage import main #导入上一级目录的\r\n\r\n\r\n# /home/zzl/PycharmProjects/py_fullstack_s4/day35/packeage/glance/api","sub_path":"py_fullstack_s4/day35/aaa/glance/api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"480609318","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(r'C:\\Users\\HP\\PycharmProjects\\Learn1\\input.jpg',0)\nheight,width = img.shape\n\n#Extract sobel edges\nsobel_x = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)\nsobel_y = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)\n\n\ncv2.imshow('original',img)\ncv2.waitKey()\ncv2.imshow('sobel_x',sobel_x)\ncv2.waitKey()\ncv2.imshow('sobel_y',sobel_y)\ncv2.waitKey()\n\nsobel_or = cv2.bitwise_or(sobel_x,sobel_y)\ncv2.imshow('sobel_or',sobel_or)\ncv2.waitKey()\n\nimg_laplacian = cv2.Laplacian(img,cv2.CV_64F)\ncv2.imshow('Laplacian',img_laplacian)\ncv2.waitKey()\n\nimg_canny = cv2.Canny(img,20,130)\ncv2.imshow('Canny',img_canny)\ncv2.waitKey()\ncv2.destroyAllWindows()\n","sub_path":"edge_detect.py","file_name":"edge_detect.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"249759133","text":"from flask import Flask, request\nfrom flask_cors import CORS\nimport records \nimport sqlite3\nimport os \nimport time \n\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n\ndef connDB(): \n return records.Database('mysql://root:5DH9awkIaNralLnd@127.0.0.1/bquest')\n\n\n\ndef getStatus( deedID ): \n db = connDB()\n\n q = \"SELECT status from Deeds where deedID = %d \" % deedID\n res = db.query(q).scalar()\n\n return res\n\n\n\ndef saveImg( deedID, image ): \n status = getStatus( deedID )\n if status == 1: \n path = \"./request-%d.png\" % deedID\n else: \n path = \"./deed-%d.png\" % deedID\n \n f = open( path, \"wb\")\n\n f.write( bytes(image) ) \n f.close()\n\ndef getImg( deedID ): \n status = getStatus( deedID )\n if status == 1: \n path = \"./request-%d.png\" % deedID\n else: \n path = \"./deed-%d.png\" % deedID\n f = open( path, \"rb\")\n img = f.read()\n f.close()\n return img \n\n\n@app.route('/')\ndef info():\n return \"beneQuest API written by Tyler Beverley, And Brandon Tran.\"\n\n@app.route('/addRequest', methods = ['POST'])\ndef addRequest():\n db = connDB()\n\n content = request.get_json(force=True)\n \n #Create a new request\n UserID = content['userID']\n Description = content['description']\n Lat = float(content['lat'])\n Long = float(content['long'])\n Img = content['image']\n Timestamp = time.time() \n q = \"\"\"INSERT INTO Deeds(requesterID, description, latitude, longitude, timestamp, upvotes, status) \n VALUES(\"%s\",\"%s\",%f,%f,%d,1,0);\"\"\" % (UserID, Description, Lat, Long, Timestamp)\n db.query(q)\n print(\"hello there\")\n\n last = \"SELECT MAX(deedID) from Deeds;\"\n res = db.query(last).scalar()\n\n saveImg( res, Img )\n return { \n \"deedID\": res\n }\n \n\n@app.route('/addDeed', methods = ['POST'])\ndef addDeed():\n db = connDB()\n\n content = request.get_json(force=True)\n print(content)\n\n #Create new request\n\n DeedID = int(content['deedID'])\n UserID = content['userID']\n Img = bytes(content['image'])\n q = \"\"\"INSERT INTO Done(userID,deedID) VALUES (%s,%d)\"\"\" % (UserID, DeedID)\n q2 = \"\"\"UPDATE Deed SET status=1 WHERE deedID = %d\"\"\" % DeedID\n\n check = \"SELECT status FROM Deeds WHERE deedID = (%d)\" % (DeedID)\n row = db.query(check)\n\n #There is no deed\n if( row.status == 1):\n print(\"Error: DeedID %d does not exist\" % (DeedID)) \n #There is a deed to complete\n else:\n db.query(q)\n db.query(q2)\n\n return \"200\"\n\n@app.route('/newUser', methods = ['GET'])\ndef newUser(): \n db = connDB()\n q = \"SELECT MAX(userID) +1 from Users\"\n newID = db.query(q).scalar()\n\n return str(newID)\n\n\n@app.route('/addUser', methods = ['POST'])\ndef addUser():\n db = connDB()\n\n content = request.get_json(force=True)\n print(content)\n\n UserID = content['userID']\n qcheck = \"SELECT * FROM Users WHERE userID = %s\" % (UserID)\n check = db.query(qcheck)\n if(check):\n print(\"Error: userID %s already exists\" % userID)\n else:\n #Need to have a default emoji set\n q = \"\"\" INSERT INTO User(userID,emoji) VALUES (%s,128512)\"\"\" % (UserID)\n db.query(q)\n\n return \"200\"\n\n\n@app.route('/upvote', methods = ['UPDATE'])\ndef upvote():\n db = connDB()\n content = request.get_json(force=True)\n\n DeedID = int(content['deedID'])\n UserID = content['userID']\n\n row = db.query(\"SELECT * FROM Upvote WHERE deedID = %d AND userID = %s\" % (DeedID,UserID))\n #Already Exists\n if(row):\n error = \"User %s has already upvoted Deed %d\" % (UserID, DeedID)\n #Create new entry\n else:\n db.query(\"INSERT INTO Upvote(userID, deedID) VALUES(%s,%d)\" % (UserID, DeedID))\n prev = db.query(\"SELECT upvotes FROM Deeds WHERE deedID = %d\" % (DeedID)).scalar()\n db.query(\"UPDATE Deeds SET upvotes = %d WHERE deedID = %d\" % (prev +1 ,DeedID))\n return \"200\"\n\n@app.route('/updateUser', methods = ['UPDATE'])\ndef updateUser():\n db = connDB()\n content = request.get_json(force=True)\n\n UserID = content['userID']\n Emoji = content['emoji']\n\n qcheck = \"SELECT * FROM Users WHERE userID = (%s)\" % (UserID)\n q = \"UPDATE Users SET emoji = %s WHERE userID = %s\" % (Emoji,UserID)\n\n\n check = db.query(qcheck)\n if(not check):\n print(\"Error: UserID %s does not exist\" % (UserID))\n else:\n db.query(q)\n\n return \"200\" \n\n@app.route('/requestsNear', methods = ['POST'])\ndef requestsNear():\n db = connDB()\n content = request.get_json(force=True)\n\n\n Lat = float(content['lat'])\n Long = float(content['long'])\n radius = 5.0\n\n q = \"\"\" SELECT * FROM Deed WHERE lat > %f\n AND lat < %f AND long > $f AND\n long < %f AND status = 0 \"\"\" % (Lat-radius,Lat+radius,Long-radius,Long+radius)\n #Not sure what we want as near\n\n row = db.query(q)\n requests = list(map (lambda r: r.deedID), record.row.all())\n return {\n \"numOfRequests\": len( requests ),\n \"deeds\": requests\n }\n\n@app.route('/allRequestsNear', methods = ['POST'])\ndef allRequestsNear():\n content = request.get_json(force=True)\n db = connDB()\n\n UserID = content['userID']\n\n rows = db.query(\"SELECT * FROM Deeds where status = 0;\")\n requests = list(map( (lambda r: r.as_dict()), rows.all() ))\n return { \n \"numRecords\": len(requests),\n \"records\": requests\n }\n\n@app.route(\"/weeklyHeros\", methods = ['POST'])\ndef weeklyHeros():\n db = connDB()\n q = \"\"\" SELECT sum(upvotes) as exp, userID, emoji FROM (\n SELECT *\n FROM Deeds\n NATURAL JOIN Done\n NATURAL JOIN Users\n ) GROUP BY userID\n ORDER BY exp\n LIMIT 10;\n \"\"\"\n row = db.query(q)\n heros = list(map( (lambda r: r.userID), record.row.all()))\n return {\n \"numOfHeros\": len( heros ),\n \"users\": heros\n }\n\n\n\n@app.route('//upvotes', methods =['POST'])\ndef upvotes( userID ): \n db = connDB()\n q = \"SELECT deedID FROM Upvote where userID = %d\" % (userID)\n row = db.query(q)\n deeds = list(map( (lambda r: r.deedID), record.row.all() ))\n return { \n \"numOfUpvotes\": len( deeds ), \n \"deeds\": deeds\n }\n\n@app.route(\"//doneDeeds\", methods = ['GET'])\ndef doneDeeds( userID ):\n db = connDB()\n\n q = \"SELECT deedID FROM Done WHERE userID = %d\" % (userID)\n row = db.query(q)\n deeds = list(map((lambda r: r.deedID), record.row.all()))\n return {\n \"numOfDeeds\": len( deeds ),\n \"deeds\": deeds\n }\n \n","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"82868335","text":"#!/usr/bin/env python3\nimport math\nfrom io import StringIO\nimport numpy as np\nimport pandas as pd\nimport re\nimport cv2\nimport pytesseract\n\n\ndef preprocessing_pipeline(img):\n # Double image size\n image_resized = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)\n # Turn to grayscale\n gray = cv2.cvtColor(image_resized, cv2.COLOR_BGR2GRAY)\n # Turn to black/white\n _, thresh = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY_INV)\n\n return thresh\n\n\ndef extract_pars(block_frame):\n pars = block_frame.par_num.unique()\n par_list = []\n for par in pars:\n par_list.append(block_frame[block_frame.par_num == par])\n return par_list\n\n\ndef extract_lines(par_frame):\n lines = par_frame.line_num.unique()\n line_list = []\n for line in lines:\n line_list.append(par_frame[par_frame.line_num == line])\n return line_list\n\n\ndef line_to_text(line_frame):\n return \" \".join(line_frame.text)\n\n\ndef postprocess_text(text):\n processed = text.lower()\n processed = re.sub(r\"[^A-Za-z0-9 ]+\", \"\", processed)\n return processed\n\n\ndef get_block(dframe, num):\n return dframe[dframe.block_num == num]\n\n\ndef rows_to_rect(frame, img_width, img_height):\n if len(frame) <= 0:\n return (0, 0, 0, 0)\n min_left = np.inf\n min_top = np.inf\n max_left = 0\n max_top = 0\n for _, row in frame.iterrows():\n start_point = (row.left, row.top)\n end_point = (start_point[0] + row.width, start_point[1] + row.height)\n if row.width > 0.5 * img_width or row.height > 0.5 * img_height:\n continue\n min_left = min(min_left, start_point[0])\n max_left = max(max_left, end_point[0])\n min_top = min(min_top, start_point[1])\n max_top = max(max_top, end_point[1])\n if min_left == np.inf or min_top == np.inf or max_left == 0 or max_top == 0:\n return (0, 0, 0, 0)\n return (min_left, min_top, max_left, max_top)\n\n\ndef add_2_blocks_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n block_1 = get_block(dframe, block_num + 1)\n block_2 = get_block(dframe, block_num + 2)\n return [\n rows_to_rect(block_1, img_width, img_height),\n rows_to_rect(block_2, img_width, img_height),\n ]\n\n\ndef add_1_blocks_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n block_1 = get_block(dframe, block_num + 1)\n return [rows_to_rect(block_1, img_width, img_height)]\n\n\ndef add_cur_block_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n block = get_block(dframe, block_num)\n rect = rows_to_rect(block, img_width, img_height)\n return [rect]\n\n\ndef add_cur_par_func(dframe, img_width, img_height, line):\n block_num = line.block_num.iloc[0]\n par_num = line.par_num.iloc[0]\n block = get_block(dframe, block_num)\n par = block[block.par_num == par_num]\n return [rows_to_rect(par, img_width, img_height)]\n\n\ndef add_cur_line_func(dframe, img_width, img_height, line_frame):\n return [rows_to_rect(line_frame, img_width, img_height)]\n\n\ndef add_form_rect(dframe, img_width, img_height, line):\n h_line = line.h_line_idx.iloc[0]\n v_line = line.v_line_idx.iloc[0]\n if not h_line or not v_line:\n return []\n rect_rows = dframe[(dframe.h_line_idx == h_line) & (dframe.v_line_idx == v_line)]\n return [rows_to_rect(rect_rows, img_width, img_height)]\n\n\ndef keyword_substr(text, keyword):\n return keyword in text\n\n\ndef keyword_isword(text, keyword):\n if keyword in text.split():\n print(\"found keyword \" + keyword)\n return keyword in text.split()\n\n\ndef get_blacken_rects(dframe, img_width, img_height):\n blacken_rects = []\n par_rects = []\n keyword_funcs = [\n (\"kunde\", keyword_substr, add_2_blocks_func),\n (\"telefon\", keyword_isword, add_cur_line_func),\n (\"telefax\", keyword_isword, add_cur_line_func),\n (\"fax\", keyword_isword, add_cur_line_func),\n (\"tel\", keyword_isword, add_cur_line_func),\n (\"fahrzeug\", keyword_isword, add_1_blocks_func),\n (\"gmbh\", keyword_isword, add_cur_block_func),\n ]\n block_nums = dframe.block_num.unique()\n for block_num in block_nums:\n cur_block = get_block(dframe, block_num)\n pars = extract_pars(cur_block)\n for par in pars:\n par_rects.append(rows_to_rect(par))\n lines = extract_lines(par)\n for line in lines:\n line = line[line.text.notna()]\n text = line_to_text(line)\n text = postprocess_text(text)\n for keyword, keyword_check, func in keyword_funcs:\n if keyword_check(text, keyword):\n blacken_rects += func(dframe, img_width, img_height, line)\n return blacken_rects, par_rects\n\n\ndef extractLines(img):\n # Preprocessing: Grayscale + Otsu\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n\n # Detect long horizontal lines\n horizontal_lines = []\n horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1))\n detect_horizontal = cv2.morphologyEx(\n thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2\n )\n cnts = cv2.findContours(\n detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE\n )\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for c in cnts:\n x_min = np.inf\n x_max = 0\n y_avg = 0\n for point in c:\n x = point[0][0]\n y = point[0][1]\n x_min = min(x_min, x)\n x_max = max(x_max, x)\n y_avg += y\n y_avg /= len(c)\n y_avg = int(y_avg)\n start = (x_min, y_avg)\n end = (x_max, y_avg)\n horizontal_lines.append((start, end))\n\n # Detect long vertical lines\n vertical_lines = []\n vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 40))\n detect_vertical = cv2.morphologyEx(\n thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2\n )\n cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for c in cnts:\n y_min = np.inf\n y_max = 0\n x_avg = 0\n for point in c:\n y = point[0][1]\n x = point[0][0]\n y_min = min(y_min, y)\n y_max = max(y_max, y)\n x_avg += x\n x_avg /= len(c)\n x_avg = int(x_avg)\n start = (x_avg, y_min)\n end = (x_avg, y_max)\n vertical_lines.append((start, end))\n\n return horizontal_lines, vertical_lines\n\n\ndef contained_horizontal(line, rect):\n return rect[0][0] < line[1][0] and rect[1][0] > line[0][0]\n\n\ndef contained_vertical(line, rect):\n return rect[0][1] < line[1][1] and rect[1][1] > line[0][1]\n\n\ndef scale_rect(rect):\n return (int(rect[0] / 2), int(rect[1] / 2), int(rect[2] / 2), int(rect[3] / 2))\n\n\ndef classify_rects(df, horizontal_lines, vertical_lines):\n h_line_idxs = []\n v_line_idxs = []\n for _, row in df.iterrows():\n rect_start = (int(row.left / 2), int(row.top) / 2)\n rect_end = (int((row.left + row.width) / 2), int((row.top + row.height) / 2))\n rect = (rect_start, rect_end)\n h_y_max = 0\n h_line_max_idx = None\n for i, line in enumerate(horizontal_lines):\n y = line[0][1]\n if contained_horizontal(line, rect) and y < rect_end[1] and y > h_y_max:\n h_y_max = y\n h_line_max_idx = i\n h_line_idxs.append(h_line_max_idx)\n\n v_x_max = 0\n v_line_max_idx = None\n for i, line in enumerate(vertical_lines):\n x = line[0][0]\n if contained_vertical(line, rect) and x < rect_end[0] and x > v_x_max:\n v_x_max = x\n v_line_max_idx = i\n v_line_idxs.append(v_line_max_idx)\n df[\"h_line_idx\"] = h_line_idxs\n df[\"v_line_idx\"] = v_line_idxs\n return df\n\n\ndef get_blacken_rects_new(dframe, img_width, img_height):\n blacken_rects = []\n keyword_funcs = [\n (\"tel\", keyword_isword, add_form_rect),\n (\"kunde\", keyword_isword, add_form_rect),\n (\"gmbh\", keyword_isword, add_cur_block_func),\n (\"tel\", keyword_isword, add_cur_line_func),\n (\"fax\", keyword_isword, add_cur_line_func),\n (\"email\", keyword_isword, add_cur_line_func),\n (\"emall\", keyword_isword, add_cur_line_func),\n (\"www\", keyword_substr, add_cur_line_func),\n (\"werksbeauftragter\", keyword_isword, add_form_rect),\n (\"abholer\", keyword_isword, add_form_rect),\n (\"baustellennummer\", keyword_substr, add_form_rect),\n (\"webseite\", keyword_isword, add_cur_line_func),\n (\"website\", keyword_isword, add_cur_line_func),\n ]\n block_nums = dframe.block_num.unique()\n for block_num in block_nums:\n cur_block = get_block(dframe, block_num)\n pars = extract_pars(cur_block)\n for par in pars:\n lines = extract_lines(par)\n for line in lines:\n line = line[line.text.notna()]\n text = line_to_text(line)\n text = postprocess_text(text)\n for keyword, keyword_check, func in keyword_funcs:\n if keyword_check(text, keyword):\n blacken_rects += func(dframe, img_width, img_height, line)\n return blacken_rects\n\n\ndef detect_text(img):\n horizontal_lines, vertical_lines = extractLines(img)\n\n pipelined_img = preprocessing_pipeline(img)\n\n img_rgb = cv2.cvtColor(pipelined_img, cv2.COLOR_BGR2RGB)\n img_height, img_width, _ = img_rgb.shape\n\n # Run Tesseract OCR over the document and read result into pandas frame\n tess_data = StringIO(pytesseract.image_to_data(img_rgb))\n df = pd.read_csv(tess_data, sep=\"\\t\")\n\n # Cleanup\n df = df.replace(r\"^\\s*$\", np.nan, regex=True)\n block_counts = df.groupby(\"block_num\")[\"text\"].count()\n non_empty_blocks = block_counts[block_counts > 0].index\n df_filled_blocks = df[df.block_num.isin(non_empty_blocks)]\n\n df_postprocessed = classify_rects(\n df_filled_blocks, horizontal_lines, vertical_lines\n )\n\n rects = get_blacken_rects_new(df_postprocessed, img_width, img_height)\n rects = list(map(scale_rect, rects))\n\n return rects\n","sub_path":"src/text_detection.py","file_name":"text_detection.py","file_ext":"py","file_size_in_byte":10326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"576484987","text":"# Create your views here.\nfrom django.core.context_processors import csrf\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom WebPenetration.models import Tutorials, Exercises\n\n\ndef managertutorials(request):\n if request.user.is_authenticated():\n tutorials = Tutorials.objects.filter(ispublic=0)\n try:\n activeId = tutorials[0].id\n content = render_to_response(\n 'ESC', {'content': tutorials.filter(id=activeId)[0].content}).content\n except:\n activeId = -1\n content = ''\n currenturl = 'managertutorials'\n data = {\n 'currenturl': currenturl,\n 'activeid': activeId,\n 'tutorials': tutorials,\n 'content': content,\n }\n data.update(csrf(request))\n return render_to_response('managertutorials.html', data)\n else:\n return HttpResponse(status=404)\n\n\ndef managerexercise(request):\n if request.user.is_authenticated():\n exercises = Exercises.objects.filter(ispublic=0)\n typeList = []\n exerciseList = []\n for exercise in exercises:\n if exercise.type not in typeList:\n typeList.append(exercise.type)\n\n for type in typeList:\n sameTypeList = []\n for exercise in exercises:\n if exercise.type == type:\n sameTypeList.append(exercise)\n exerciseList.append(sameTypeList)\n currenturl = 'managerexercise'\n data = {\n 'currenturl': currenturl,\n 'exercises': exerciseList,\n }\n data.update(csrf(request))\n return render_to_response('managerexercise.html', data)\n else:\n return HttpResponse(status=404)\n\n\ndef managerlogin(request):\n return render_to_response('login.html')\n\n\ndef postmanagertutor(request):\n if request.user.is_authenticated():\n if request.method == 'POST':\n id = request.POST.get('id')\n pb = request.POST.get('pb')\n try:\n if pb == u'tutor' or pb == u'joyful' or pb == u'tutordelete':\n tutorial = Tutorials.objects.get(id=id)\n if pb == u'tutordelete' and tutorial.ispublic == 0:\n tutorial.delete()\n return HttpResponse('success')\n elif pb == u'tutor' and tutorial.ispublic == 0:\n tutorial.ispublic = 1\n tutorial.save()\n return HttpResponse('success')\n elif pb == u'joyful'and tutorial.ispublic == 0:\n tutorial.ispublic = 2\n tutorial.save()\n return HttpResponse('success')\n elif pb == u'exerc' or pb == u'exercdelete':\n exercise = Exercises.objects.get(id=id)\n if pb == u'exerc'and exercise.ispublic == 0:\n exercise.ispublic = 1\n exercise.save()\n return HttpResponse('success')\n elif pb == u'exercdelete' and exercise.ispublic == 0:\n exercise.delete()\n return HttpResponse('success')\n except:\n pass\n return HttpResponse('')\n else:\n return HttpResponse(status=404)\n","sub_path":"adminmanager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"403508915","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\n# TODO: обоюдное выделеление текста в полях ввода\n# TODO: конвертирование в обе стороны\n\n\nif __name__ == '__main__':\n from os.path import split as path_split\n import traceback\n import sys\n\n from PySide.QtGui import *\n from PySide.QtCore import *\n\n import hex2str\n\n app = QApplication(sys.argv)\n\n mainWidget = QWidget()\n mainWidget.setWindowTitle(path_split(__file__)[1])\n\n layout = QVBoxLayout()\n\n text_edit_input = QPlainTextEdit()\n text_edit_output = QPlainTextEdit()\n\n last_select_start, last_select_end = None, None\n\n# def selection_changed():\n# \"\"\"Обновляем выделение у текстовых редакторов\"\"\"\n#\n# # text_edit_input -- hex значения\n# # text_edit_output -- строковые значения, каждые два hex представляютсяодним символом\n#\n#\n# # cursor.selectionEnd()\n# #\n# # QTextCursor::MoveAnchor\t0\tMoves the anchor to the same position as the cursor itself.\n# # QTextCursor::KeepAnchor\t1\tKeeps the anchor where it is.\n# #\n# # void QTextCursor::setPosition ( int pos, MoveMode m = MoveAnchor )\n# # bool QTextCursor::movePosition ( MoveOperation operation, MoveMode mode = MoveAnchor, int n = 1 )\n#\n# global last_select_start, last_select_end\n#\n# if text_edit_input.hasFocus():\n# cursor = QTextCursor(text_edit_input.textCursor())\n# start, end = cursor.selectionStart(), cursor.selectionEnd()\n# selection_len = len(cursor.selectedText())\n#\n# if selection_len == 0:\n# last_select_start, last_select_end = start, end\n# return\n#\n# if last_select_start == start and last_select_end == end:\n# return\n#\n# print('start={} end={} len={}'.format(start, end, selection_len)\n# + ' | ' + 'last_start={} last_end={}'.format(last_select_start, last_select_end))\n#\n# if last_select_end is not None and end >= last_select_end:\n# # if True:\n# n = selection_len\n# # # if n % 2 == 1 and n > 1:\n# # # n -= 1\n# # # elif n == 1:\n# # # n = 2\n#\n# cursor.setPosition(start, QTextCursor.MoveAnchor)\n#\n# # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # n += 1\n# # cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, n)\n#\n# # cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, n)\n#\n# # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # n += 1\n# if n % 2 == 1:\n# n += 1\n#\n# # print('r', selection_len, n)\n#\n# cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, n)\n# text_edit_input.setTextCursor(cursor)\n#\n# # elif last_select_start is not None and last_select_start < start:\n# elif last_select_start is not None and start < last_select_start:\n# n = selection_len\n# # # if n % 2 == 1 and n > 1:\n# # # n -= 1\n# # # elif n == 1:\n# # # n = 2\n#\n# cursor.setPosition(end, QTextCursor.MoveAnchor)\n#\n# # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # n += 1\n# # cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, n)\n#\n# # cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, n)\n#\n# # # if n % 2 == 1 and start < last_select_start and last_select_start is not None:\n# # # n += 1\n# # if n % 2 == 1:\n# # n -= 1\n#\n# cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, n)\n# text_edit_input.setTextCursor(cursor)\n#\n# last_select_start, last_select_end = start, end\n#\n# # if text_edit_input.hasFocus():\n# # cursor = QTextCursor(text_edit_input.textCursor())\n# #\n# # start, end = cursor.selectionStart(), cursor.selectionEnd()\n# #\n# # cursor.setPosition(start // 2, QTextCursor.MoveAnchor)\n# # cursor.movePosition(QTextCursor.Right if end > start else QTextCursor.Left, QTextCursor.KeepAnchor, (max(end, start) - min(end, start)) / 2)\n# #\n# # print(start, (max(end, start) - min(end, start)), (max(end, start) - min(end, start)) / 2)\n# #\n# # text_edit_output.setTextCursor(cursor)\n# #\n# # elif text_edit_output.hasFocus():\n# # cursor = QTextCursor(text_edit_output.textCursor())\n# # text_edit_input.setTextCursor(cursor)\n#\n# text_edit_input.selectionChanged.connect(selection_changed)\n# text_edit_output.selectionChanged.connect(selection_changed)\n\n label_error = QLabel()\n label_error.setStyleSheet(\"QLabel { color : red; }\")\n label_error.setTextInteractionFlags(Qt.TextSelectableByMouse)\n label_error.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)\n button_detail_error = QPushButton('...')\n button_detail_error.setFixedSize(20, 20)\n button_detail_error.setToolTip('Detail error')\n last_error_message = None\n last_detail_error_message = None\n\n def show_detail_error_massage():\n message = last_error_message + '\\n\\n' + last_detail_error_message\n\n mb = QErrorMessage()\n mb.setWindowTitle('Error')\n # Сообщение ошибки содержит отступы, символы-переходы на следующую строку,\n # которые поломаются при вставке через QErrorMessage.showMessage, и нет возможности\n # выбрать тип текста, то делаем такой хак.\n mb.findChild(QTextEdit).setPlainText(message)\n\n mb.exec_()\n\n button_detail_error.clicked.connect(show_detail_error_massage)\n\n def input_text_changed():\n label_error.clear()\n button_detail_error.hide()\n\n global last_error_message, last_detail_error_message\n last_error_message = None\n last_detail_error_message = None\n\n try:\n text = text_edit_input.toPlainText()\n text = hex2str.do(text)\n text_edit_output.setPlainText(text)\n except Exception as e:\n # Выводим ошибку в консоль\n traceback.print_exc()\n\n # Сохраняем в переменную\n tb = traceback.format_exc()\n\n last_error_message = str(e)\n last_detail_error_message = str(tb)\n button_detail_error.show()\n\n label_error.setText('Error: ' + last_error_message)\n\n text_edit_input.textChanged.connect(input_text_changed)\n\n text_edit_input.setPlainText('504F53542068747470733A')\n\n splitter = QSplitter()\n splitter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n splitter.addWidget(text_edit_input)\n splitter.addWidget(text_edit_output)\n\n layout.addWidget(splitter)\n\n layout_error = QHBoxLayout()\n layout_error.addWidget(label_error)\n layout_error.addWidget(button_detail_error)\n\n layout.addLayout(layout_error)\n\n mainWidget.setLayout(layout)\n\n mainWidget.resize(650, 500)\n mainWidget.show()\n\n sys.exit(app.exec_())\n","sub_path":"hex2str/hex2str-gui.py","file_name":"hex2str-gui.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"205247959","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2018, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n# Before you can use the jobs API, you need to set up an access token.\n# Log in to the IBM Q experience. Under \"Account\", generate a personal\n# access token. Replace 'PUT_YOUR_API_TOKEN_HERE' below with the quoted\n# token string. Uncomment the APItoken variable, and you will be ready to go.\n\nAPItoken = 'Token'\nif 'APItoken' not in locals():\n raise Exception('Please set up your access token. See Qconfig.py.')\n","sub_path":"2018-07-19_oscon_gambetta/Qconfig.py","file_name":"Qconfig.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"563133864","text":"from collections import Callable\n\nimport numpy as np\n\n\ndef linear_kernel_func(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return support_vec.T * vec\n\n\ndef poly_kernel_func(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return (1 + support_vec.T * vec) ** 2\n\n\ndef gauss_kernel_func(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return np.exp(-(np.linalg.norm(support_vec - vec) ** 2) / 0.8)\n\n\ndef gauss_kernel_func_n(support_vec: np.ndarray, vec: np.ndarray) -> float:\n return np.exp(-(np.linalg.norm(support_vec - vec) ** 2) / 0.2)\n\n\nclass SorSvr(object):\n def __init__(self, epsilon: float = 0.1, sor_epsilon: float = 0.001,\n omega: float = 0.5, C: int = 100, kernel: Callable = gauss_kernel_func):\n \"\"\"\n Constructor\n\n :param epsilon: threshold for predicted function insensitivity\n :param sor_epsilon: threshold for SOR solver\n :param omega: magic const for SOR solver. Need to be in (0, 2)\n :param C: magic const for Lagrange function ¯\\_(ツ)_/¯\n :param kernel: kernel function for \"kernel trick\"\n \"\"\"\n self.epsilon = epsilon\n self.sor_epsilon = sor_epsilon\n self.C = C\n self.omega = omega\n self.kernel = kernel\n self.dim = 0\n self.support_vecs = []\n self.support_vecs_coeffs = []\n self.b = 0.0\n\n def _sor_solver(self, A, b, initial_guess):\n \"\"\"\n This is an implementation of the pseudo-code provided in the Wikipedia article.\n Arguments:\n A: nxn numpy matrix.\n b: n dimensional numpy vector.\n initial_guess: An initial solution guess for the solver to start with.\n Returns:\n phi: solution vector of dimension n.\n \"\"\"\n phi = initial_guess[:]\n residual = np.inf\n iter_count = 0\n while residual > self.sor_epsilon:\n iter_count += 1\n old_phi = phi.copy()\n for i in range(A.shape[0]):\n sigma = 0\n for j in range(A.shape[1]):\n if j != i:\n sigma += A[i][j] * phi[j]\n phi[i] = (1 - self.omega) * phi[i] + (self.omega / A[i][i]) * (b[i] - sigma)\n # phi[i] = phi[i] + (self.omega / A[i][i]) * (b[i] - sigma)\n if phi[i] < 0:\n phi[i] = 0\n elif phi[i] > self.C:\n phi[i] = self.C\n residual = np.linalg.norm(phi - old_phi)\n print('Residual: {0:10.6g}'.format(residual))\n print(\"\\n~~~~~~ Iters count: {} ~~~~~~\\n\".format(iter_count))\n return phi\n\n def train(self, x_train: np.ndarray, y_train: np.ndarray):\n self.dim = len(x_train)\n # Create matrices from article yong2004\n x = x_train.reshape((self.dim, 1))\n y = y_train.reshape((self.dim, 1))\n d = np.ones((2 * self.dim, 1))\n d[self.dim:] *= -1\n c = np.full(shape=(2 * self.dim, 1), fill_value=-self.epsilon, dtype=np.float)\n c[:self.dim] += y\n c[self.dim:] += -y\n H = d * d.T\n for i in range(H.shape[0]):\n for j in range(H.shape[1]):\n x1 = x[i] if i < self.dim else x[i - self.dim]\n x2 = x[j] if j < self.dim else x[j - self.dim]\n H[i][j] *= self.kernel(x1, x2)\n E = d * d.T\n A = H + E\n # Find Lagrange multipliers by SOR algorithm\n a = self._sor_solver(A, c.reshape((2 * self.dim)), np.zeros(2 * self.dim))\n # Get support vectors and their coeffs (a_i - a*_i)\n self.support_vecs = []\n self.support_vecs_coeffs = []\n for i in range(0, self.dim):\n if not np.isclose(a[i], 0) or not np.isclose(a[self.dim + i], 0):\n self.support_vecs.append(x[i])\n self.support_vecs_coeffs.append(a[i] - a[self.dim + i])\n self.b = sum(self.support_vecs_coeffs)\n\n def predict(self, x: np.ndarray) -> float:\n res = 0.0\n for i in range(0, len(self.support_vecs)):\n res += self.support_vecs_coeffs[i] * self.kernel(self.support_vecs[i], x)\n return res + self.b\n\n def get_support_vecs(self):\n return self.support_vecs\n","sub_path":"sor_svr.py","file_name":"sor_svr.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"420212238","text":"\"\"\"\nModule holds selenium stuff\n\"\"\"\nfrom abc import abstractmethod\n\nimport os\nimport time\nimport shutil\nimport sys\nimport subprocess\nimport urwid\n\nfrom collections import Counter\nfrom bzt.engine import ScenarioExecutor, Scenario\nfrom bzt.utils import RequiredTool, shell_exec, shutdown_process, BetterDict, JavaVM\nfrom bzt.moves import string_types, text_type\nfrom bzt.modules.aggregator import ConsolidatingAggregator, ResultsReader\nfrom bzt.modules.console import WidgetProvider\n\n\nclass SeleniumExecutor(ScenarioExecutor, WidgetProvider):\n \"\"\"\n Selenium executor\n \"\"\"\n SELENIUM_DOWNLOAD_LINK = \"http://selenium-release.storage.googleapis.com/{version}/\" \\\n \"selenium-server-standalone-{version}.0.jar\"\n SELENIUM_VERSION = \"2.46\"\n\n JUNIT_DOWNLOAD_LINK = \"http://search.maven.org/remotecontent?filepath=junit/junit/{version}/junit-{version}.jar\"\n JUNIT_VERSION = \"4.12\"\n\n SUPPORTED_TYPES = [\".py\", \".jar\", \".java\"]\n\n def __init__(self):\n super(SeleniumExecutor, self).__init__()\n self.start_time = None\n self.end_time = None\n self.runner = None\n self.widget = None\n self.reader = None\n self.kpi_file = None\n\n def prepare(self):\n \"\"\"\n 1) Locate script or folder\n 2) detect script type\n 3) create runner instance, prepare runner\n \"\"\"\n scenario = self.get_scenario()\n self.kpi_file = self.engine.create_artifact(\"selenium_tests_report\", \".txt\")\n script_type, script_is_folder = self.detect_script_type(scenario.get(\"script\"))\n runner_config = BetterDict()\n\n if script_type == \".py\":\n self.runner = NoseTester\n runner_config = self.settings.get(\"selenium-tools\").get(\"nose\")\n\n elif script_type == \".jar\" or script_type == \".java\":\n self.runner = JunitTester\n runner_config = self.settings.get(\"selenium-tools\").get(\"junit\")\n\n runner_config[\"script-type\"] = script_type\n runner_working_dir = self.engine.create_artifact(runner_config.get(\"working-dir\", \"classes\"), \"\")\n runner_config[\"working-dir\"] = runner_working_dir\n runner_config.get(\"artifacts-dir\", self.engine.artifacts_dir)\n runner_config.get(\"working-dir\", runner_working_dir)\n runner_config.get(\"report-file\", self.kpi_file)\n\n if Scenario.SCRIPT in scenario:\n if script_is_folder:\n shutil.copytree(scenario.get(\"script\"), runner_working_dir)\n else:\n os.makedirs(runner_working_dir)\n shutil.copy2(scenario.get(\"script\"), runner_working_dir)\n\n self.runner = self.runner(runner_config, scenario, self.log)\n self.runner.prepare()\n self.reader = SeleniumDataReader(self.kpi_file, self.log)\n if isinstance(self.engine.aggregator, ConsolidatingAggregator):\n self.engine.aggregator.add_underling(self.reader)\n\n def detect_script_type(self, script_path):\n \"\"\"\n checks if script is java or python\n if it's folder or single script\n :return:\n \"\"\"\n if not isinstance(script_path, string_types) and not isinstance(script_path, text_type):\n raise RuntimeError(\"Nothing to test, no files were provided in scenario\")\n script_path_is_directory = False\n test_files = []\n for dir_entry in os.walk(script_path):\n if dir_entry[2]:\n for test_file in dir_entry[2]:\n if os.path.splitext(test_file)[1].lower() in SeleniumExecutor.SUPPORTED_TYPES:\n test_files.append(test_file)\n\n if os.path.isdir(script_path):\n file_ext = os.path.splitext(test_files[0])[1].lower()\n script_path_is_directory = True\n else:\n file_ext = os.path.splitext(script_path)[1]\n\n if file_ext not in SeleniumExecutor.SUPPORTED_TYPES:\n raise RuntimeError(\"Supported tests types %s was not found\" % SeleniumExecutor.SUPPORTED_TYPES)\n return file_ext, script_path_is_directory\n\n def startup(self):\n \"\"\"\n Start runner\n :return:\n \"\"\"\n self.start_time = time.time()\n self.runner.run_tests()\n\n def check(self):\n \"\"\"\n check if test completed\n :return:\n \"\"\"\n if self.widget:\n cur_state = self.reader.get_state()\n self.widget.update(cur_state, self.reader.summary)\n\n return self.runner.is_finished()\n\n def shutdown(self):\n \"\"\"\n shutdown test_runner\n :return:\n \"\"\"\n self.runner.shutdown()\n\n if self.start_time:\n self.end_time = time.time()\n self.log.debug(\"Selenium tests ran for %s seconds\", self.end_time - self.start_time)\n\n if self.kpi_file:\n if (not os.path.exists(self.kpi_file) or not os.path.getsize(self.kpi_file)) and not self.runner.is_failed:\n msg = \"Empty runner report, most likely runner failed: %s\"\n raise RuntimeWarning(msg % self.kpi_file)\n\n def get_widget(self):\n if not self.widget:\n self.widget = SeleniumWidget(self.get_scenario().get(\"script\"))\n return self.widget\n\n\nclass AbstractTestRunner(object):\n \"\"\"\n Abstract test runner\n \"\"\"\n\n def __init__(self, settings, scenario):\n self.process = None\n self.settings = settings\n self.required_tools = []\n self.scenario = scenario\n self.report_file = self.settings.get(\"report-file\")\n self.artifacts_dir = self.settings.get(\"artifacts-dir\")\n self.working_dir = self.settings.get(\"working-dir\")\n self.log = None\n self.opened_descriptors = {\"std_err\": None, \"std_out\": None}\n self.is_failed = False\n\n @abstractmethod\n def prepare(self):\n pass\n\n @abstractmethod\n def run_checklist(self):\n pass\n\n @abstractmethod\n def run_tests(self):\n pass\n\n def is_finished(self):\n ret_code = self.process.poll()\n if ret_code is not None:\n if ret_code != 0:\n self.log.debug(\"Test runner exit code: %s\", ret_code)\n with open(self.opened_descriptors[\"std_err\"].name) as fds:\n std_err = fds.read()\n self.is_failed = True\n raise RuntimeError(\"Test runner %s has failed: %s\" % (self.__class__.__name__, std_err.strip()))\n return True\n return False\n\n def check_tools(self):\n for tool in self.required_tools:\n if not tool.check_if_installed():\n self.log.info(\"Installing %s\", tool.tool_name)\n tool.install()\n\n def shutdown(self):\n shutdown_process(self.process, self.log)\n for desc in self.opened_descriptors.values():\n desc.close()\n self.opened_descriptors = {}\n\n\nclass JunitTester(AbstractTestRunner):\n \"\"\"\n Allows to test java and jar files\n \"\"\"\n\n def __init__(self, junit_config, scenario, parent_logger):\n super(JunitTester, self).__init__(junit_config, scenario)\n self.log = parent_logger.getChild(self.__class__.__name__)\n path_lambda = lambda key, val: os.path.abspath(os.path.expanduser(self.settings.get(key, val)))\n\n self.junit_path = path_lambda(\"path\", \"~/.bzt/selenium-taurus/tools/junit/junit.jar\")\n self.selenium_server_jar_path = path_lambda(\"selenium-server\", \"~/.bzt/selenium-taurus/selenium-server.jar\")\n self.junit_listener_path = os.path.join(os.path.dirname(__file__), \"resources\", \"taurus_junit.jar\")\n\n self.base_class_path = [self.selenium_server_jar_path, self.junit_path, self.junit_listener_path]\n self.base_class_path.extend(self.scenario.get(\"additional-classpath\", []))\n\n def prepare(self):\n \"\"\"\n run checklist, make jar.\n \"\"\"\n self.run_checklist()\n\n if self.settings.get(\"script-type\", None) == \".java\":\n self.compile_scripts()\n\n def run_checklist(self):\n \"\"\"\n java\n javac\n selenium-server.jar\n junit.jar\n junit_listener.jar\n \"\"\"\n\n if self.settings.get(\"script_type\", None) == \".java\":\n self.required_tools.append(JavaC(\"\", \"\", self.log))\n self.required_tools.append(JavaVM(\"\", \"\", self.log))\n self.required_tools.append(SeleniumServerJar(self.selenium_server_jar_path,\n SeleniumExecutor.SELENIUM_DOWNLOAD_LINK.format(\n version=SeleniumExecutor.SELENIUM_VERSION), self.log))\n self.required_tools.append(JUnitJar(self.junit_path, SeleniumExecutor.JUNIT_DOWNLOAD_LINK.format(\n version=SeleniumExecutor.JUNIT_VERSION)))\n self.required_tools.append(JUnitListenerJar(self.junit_listener_path, \"\"))\n\n self.check_tools()\n\n def compile_scripts(self):\n \"\"\"\n Compile .java files\n \"\"\"\n self.log.debug(\"Compiling .java files started\")\n java_files = []\n\n for dir_entry in os.walk(self.working_dir):\n if dir_entry[2]:\n for test_file in dir_entry[2]:\n if os.path.splitext(test_file)[1].lower() == \".java\":\n java_files.append(os.path.join(dir_entry[0], test_file))\n\n compile_cl = [\"javac\", \"-cp\", os.pathsep.join(self.base_class_path)]\n compile_cl.extend(java_files)\n\n with open(os.path.join(self.artifacts_dir, \"javac_out\"), 'ab') as javac_out:\n with open(os.path.join(self.artifacts_dir, \"javac_err\"), 'ab') as javac_err:\n self.process = shell_exec(compile_cl, cwd=self.working_dir, stdout=javac_out, stderr=javac_err)\n ret_code = self.process.poll()\n\n while ret_code is None:\n self.log.debug(\"Compiling .java files...\")\n time.sleep(1)\n ret_code = self.process.poll()\n\n if ret_code != 0:\n self.log.debug(\"javac exit code: %s\", ret_code)\n with open(javac_err.name) as err_file:\n out = err_file.read()\n raise RuntimeError(\"Javac exited with error:\\n %s\" % out.strip())\n\n self.log.info(\"Compiling .java files completed\")\n\n self.make_jar()\n\n def make_jar(self):\n \"\"\"\n move all .class files to compiled.jar\n \"\"\"\n self.log.debug(\"Making .jar started\")\n\n with open(os.path.join(self.artifacts_dir, \"jar_out\"), 'ab') as jar_out:\n with open(os.path.join(self.artifacts_dir, \"jar_err\"), 'ab') as jar_err:\n class_files = [java_file for java_file in os.listdir(self.working_dir) if java_file.endswith(\".class\")]\n jar_name = self.settings.get(\"jar-name\", \"compiled.jar\")\n if class_files:\n compile_jar_cl = [\"jar\", \"-cf\", jar_name]\n compile_jar_cl.extend(class_files)\n else:\n package_dir = os.listdir(self.working_dir)[0]\n compile_jar_cl = [\"jar\", \"-cf\", jar_name, \"-C\", package_dir, \".\"]\n\n self.process = shell_exec(compile_jar_cl, cwd=self.working_dir, stdout=jar_out, stderr=jar_err)\n ret_code = self.process.poll()\n\n while ret_code is None:\n self.log.debug(\"Making jar file...\")\n time.sleep(1)\n ret_code = self.process.poll()\n\n if ret_code != 0:\n with open(jar_err.name) as err_file:\n out = err_file.read()\n self.log.info(\"Making jar failed with code %s\", ret_code)\n self.log.info(\"jar output: %s\", out)\n raise RuntimeError(\"Jar exited with non-zero code\")\n\n self.log.info(\"Making .jar file completed\")\n\n def run_tests(self):\n # java -cp junit.jar:selenium-test-small.jar:\n # selenium-2.46.0/selenium-java-2.46.0.jar:./../selenium-server.jar\n # org.junit.runner.JUnitCore TestBlazemeterPass\n\n jar_list = [os.path.join(self.working_dir, jar) for jar in os.listdir(self.working_dir) if jar.endswith(\".jar\")]\n self.base_class_path.extend(jar_list)\n\n junit_command_line = [\"java\", \"-cp\", os.pathsep.join(self.base_class_path),\n \"taurus_junit_listener.CustomRunner\"]\n junit_command_line.extend(jar_list)\n junit_command_line.extend([self.report_file])\n\n junit_out_path = os.path.join(self.artifacts_dir, \"junit_out\")\n junit_err_path = os.path.join(self.artifacts_dir, \"junit_err\")\n\n junit_out = open(junit_out_path, 'ab')\n junit_err = open(junit_err_path, 'ab')\n\n self.opened_descriptors[\"std_out\"] = junit_out\n self.opened_descriptors[\"std_err\"] = junit_err\n\n self.process = shell_exec(junit_command_line, cwd=self.artifacts_dir,\n stdout=junit_out,\n stderr=junit_err)\n\n\nclass NoseTester(AbstractTestRunner):\n \"\"\"\n Python selenium tests runner\n \"\"\"\n\n def __init__(self, nose_config, scenario, parent_logger):\n super(NoseTester, self).__init__(nose_config, scenario)\n self.log = parent_logger.getChild(self.__class__.__name__)\n self.plugin_path = os.path.join(os.path.dirname(__file__), \"resources\", \"nose_plugin.py\")\n\n def prepare(self):\n self.run_checklist()\n\n def run_checklist(self):\n \"\"\"\n we need installed nose plugin\n \"\"\"\n if sys.version >= '3':\n self.log.warn(\"You are using python3, make sure that your scripts are able to run in python3!\")\n\n self.required_tools.append(\n TaurusNosePlugin(self.plugin_path, \"\"))\n\n self.check_tools()\n\n def run_tests(self):\n \"\"\"\n run python tests\n \"\"\"\n executable = self.settings.get(\"interpreter\", sys.executable)\n nose_command_line = [executable, self.plugin_path, self.report_file, self.working_dir]\n nose_out = open(os.path.join(self.artifacts_dir, \"nose_out\"), 'ab')\n nose_err = open(os.path.join(self.artifacts_dir, \"nose_err\"), 'ab')\n\n self.opened_descriptors[\"std_out\"] = nose_out\n self.opened_descriptors[\"std_err\"] = nose_err\n\n self.process = shell_exec(nose_command_line, cwd=self.artifacts_dir,\n stdout=nose_out,\n stderr=nose_err)\n\n\nclass SeleniumDataReader(ResultsReader):\n \"\"\"\n Read KPI from data log\n \"\"\"\n\n def __init__(self, filename, parent_logger):\n super(SeleniumDataReader, self).__init__()\n self.log = parent_logger.getChild(self.__class__.__name__)\n self.filename = filename\n self.fds = None\n self.partial_buffer = \"\"\n self.test_buffer = TestSample()\n self.offset = 0\n self.trace_buff = \"\"\n self.err_message_buff = \"\"\n self.err_codes = {\"OK\": \"200\", \"SKIPPED\": \"300\", \"FAILED\": \"404\", \"ERROR\": \"500\"}\n self.summary = Counter({\"total\": 0, \"pass\": 0, \"fail\": 0})\n\n def _read(self, last_pass=False):\n \"\"\"\n :param last_pass:\n \"\"\"\n\n while not self.fds and not self.__open_fds():\n self.log.debug(\"No data to start reading yet...\")\n yield None\n\n self.log.debug(\"Reading selenium results\")\n self.fds.seek(self.offset) # without this we have a stuck reads on Mac\n if last_pass:\n lines = self.fds.readlines() # unlimited\n else:\n lines = self.fds.readlines(1024 * 1024) # 1MB limit to read\n self.offset = self.fds.tell()\n for line in lines:\n if not line.endswith(\"\\n\"):\n self.partial_buffer += line\n continue\n\n line = \"%s%s\" % (self.partial_buffer, line)\n self.partial_buffer = \"\"\n line = line.strip(\"\\n\")\n # TODO: Optimise it\n if line.startswith(\"--TIMESTAMP:\"):\n self.test_buffer = TestSample()\n self.trace_buff = \"\"\n self.err_message_buff = \"\"\n self.test_buffer.t_stamp = line[12:]\n elif line.startswith(\"--MODULE:\"):\n self.test_buffer.module = line[9:]\n elif line.startswith(\"--RUN:\"):\n self.test_buffer.test_name = line[6:]\n elif line.startswith(\"--RESULT:\"):\n self.test_buffer.result = line[10:]\n elif line.startswith(\"--TRACE:\"):\n self.trace_buff = line[8:]\n elif line.startswith(\"--MESSAGE:\"):\n self.err_message_buff = line[9:]\n elif line.startswith(\"--TIME:\"):\n self.summary['total'] += 1\n self.test_buffer.time = line[7:]\n self.test_buffer.trace = self.trace_buff\n self.test_buffer.message = self.err_message_buff\n\n r_code = self.err_codes[self.test_buffer.result]\n concur = 1\n conn_time = 0\n latency = 0\n\n if self.test_buffer.trace or self.test_buffer.message:\n self.summary[\"fail\"] += 1\n if not self.test_buffer.message:\n error = self.test_buffer.trace\n else:\n error = self.test_buffer.message + \"\\n\" + self.test_buffer.trace\n else:\n self.summary[\"pass\"] += 1\n error = None\n yield int(self.test_buffer.t_stamp) / 1000.0, self.test_buffer.test_name, concur, \\\n int(self.test_buffer.time) / 1000.0, conn_time, latency, r_code, error, self.test_buffer.module\n else:\n if not self.err_message_buff:\n self.trace_buff += line\n else:\n self.err_message_buff += line\n\n def get_state(self):\n return self.test_buffer.test_name\n\n def __open_fds(self):\n \"\"\"\n opens results.txt\n \"\"\"\n if not os.path.isfile(self.filename):\n self.log.debug(\"File not appeared yet\")\n return False\n\n if not os.path.getsize(self.filename):\n self.log.debug(\"File is empty: %s\", self.filename)\n return False\n\n self.fds = open(self.filename)\n return True\n\n def __del__(self):\n if self.fds:\n self.fds.close()\n\n\nclass TestSample(object):\n def __init__(self):\n self.t_stamp = \"\"\n self.module = \"\"\n self.test_name = \"\"\n self.result = \"\"\n self.trace = \"\"\n self.message = \"\"\n self.time = \"\"\n\n\nclass SeleniumWidget(urwid.Pile):\n def __init__(self, script):\n widgets = []\n self.script_name = urwid.Text(\"Tests: %s\" % script)\n self.summary_stats = urwid.Text(\"\")\n self.current_test = urwid.Text(\"\")\n widgets.append(self.script_name)\n widgets.append(self.summary_stats)\n widgets.append(self.current_test)\n super(SeleniumWidget, self).__init__(widgets)\n\n def update(self, cur_test, reader_summary):\n self.current_test.set_text(cur_test)\n self.summary_stats.set_text(\n \"Total:%d Pass:%d Fail:%d\" % (reader_summary['total'], reader_summary['pass'], reader_summary['fail']))\n self._invalidate()\n\n\nclass SeleniumServerJar(RequiredTool):\n def __init__(self, tool_path, download_link, parent_logger):\n super(SeleniumServerJar, self).__init__(\"Selenium server\", tool_path, download_link)\n self.log = parent_logger.getChild(self.__class__.__name__)\n\n def check_if_installed(self):\n self.log.debug(\"%s path: %s\", self.tool_name, self.tool_path)\n selenium_launch_command = [\"java\", \"-jar\", self.tool_path, \"-help\"]\n selenium_subproc = shell_exec(selenium_launch_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = selenium_subproc.communicate()\n self.log.debug(\"%s output: %s\", self.tool_name, output)\n if selenium_subproc.returncode == 0:\n self.already_installed = True\n return True\n else:\n return False\n\n\nclass JUnitJar(RequiredTool):\n def __init__(self, tool_path, download_link):\n super(JUnitJar, self).__init__(\"JUnit\", tool_path, download_link)\n\nclass JavaC(RequiredTool):\n def __init__(self, tool_path, download_link, parent_logger):\n super(JavaC, self).__init__(\"JavaC\", tool_path, download_link)\n self.log = parent_logger.getChild(self.__class__.__name__)\n\n def check_if_installed(self):\n try:\n output = subprocess.check_output([\"javac\", '-version'], stderr=subprocess.STDOUT)\n self.log.debug(\"%s output: %s\", self.tool_name, output)\n return True\n except BaseException:\n raise RuntimeError(\"The %s is not operable or not available. Consider installing it\" % self.tool_name)\n\n def install(self):\n raise NotImplementedError()\n\n\nclass JUnitListenerJar(RequiredTool):\n def __init__(self, tool_path, download_link):\n super(JUnitListenerJar, self).__init__(\"JUnitListener\", tool_path, download_link)\n\n def install(self):\n raise NotImplementedError()\n\n\nclass TaurusNosePlugin(RequiredTool):\n def __init__(self, tool_path, download_link):\n super(TaurusNosePlugin, self).__init__(\"TaurusNosePlugin\", tool_path, download_link)\n\n def install(self):\n raise NotImplementedError()\n","sub_path":"bzt/modules/selenium.py","file_name":"selenium.py","file_ext":"py","file_size_in_byte":21508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"596014574","text":"\n\nclass fileNotFoundException( Exception ): \n \"\"\" Exception when a file is not found\"\"\"\n filePath = None\n message = None\n \n def __init__( self, filePath ):\n Exception.__init__( self, filePath ) \n self.filePath = filePath\n self.message = 'Parameter file not found: ' + self.filePath + '\\n\\n'\n \n # Exceptions\nclass directoryNotEmpty( Exception ): \n \"\"\" Directory not empty exception \"\"\"\n def __init__( self, directoryPath ):\n Exception.__init__( self, directoryPath )\n self.directoryPath = directoryPath\n self.message = 'The directory is not empty: ' + self.directoryPath + '\\n\\nChoose a different one\\n'\n \n \n \n \nclass fatalError( Exception ): \n \"\"\" Fatal error exception \"\"\"\n \n def __init__( self, mainErrorMessage ,*detailsMessages):\n \"\"\" Constructor \"\"\"\n \n super(fatalError,self).__init__( self, mainErrorMessage ,*detailsMessages)\n \n self.mainErrorMessage = mainErrorMessage\n \n self.message = \" \" + mainErrorMessage + '\\n\\n'\n \n if len(detailsMessages) > 0:\n self.message += \"Details:\" + \"\\n\"\n for message in detailsMessages:\n self.message += message + '\\n'\n \n self.message +='\\n'\n \n \n def __str__(self):\n return self.message \n \n def __repr__(self): \n return self.message \n","sub_path":"pyWAT/core/errorHandling.py","file_name":"errorHandling.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"92530483","text":"# Copyright 2015 Mirantis Inc.\n# Copyright 2014 Symantec Corporation\n# All Rights Reserved.\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\nfrom magnetodb.openstack.common import log as logging\nfrom magnetodb import storage\nfrom magnetodb.common import exception\n\nLOG = logging.getLogger(__name__)\n\n\nclass ProjectUsageController():\n \"\"\"Returns metrics.\n \"\"\"\n\n def project_usage_details(self, req, project_id):\n req.context.tenant = project_id\n\n if 'metrics' not in req.GET:\n keys = ['size', 'item_count']\n else:\n keys = req.GET['metrics'].split(',')\n\n table_names = storage.list_tables(req.context)\n\n result = []\n for table_name in table_names:\n try:\n result.append({\n \"table_name\": table_name,\n \"usage_detailes\": storage.get_table_statistics(req.context,\n table_name,\n keys)\n })\n except exception.ValidationError:\n pass\n\n return result\n","sub_path":"magnetodb/api/openstack/v1/monitoring/project_usage_details.py","file_name":"project_usage_details.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"206860216","text":"import unittest\nimport torch\nfrom pytorch_metric_learning.losses import LargeMarginSoftmaxLoss, SphereFaceLoss\nfrom pytorch_metric_learning.utils import common_functions as c_f\nimport math\nimport scipy\nimport numpy as np\n\nclass TestLargeMarginSoftmaxLoss(unittest.TestCase):\n def test_large_margin_softmax_and_sphereface_loss(self):\n margin = 10\n scale = 2\n loss_funcA = LargeMarginSoftmaxLoss(margin=margin, scale=scale, num_classes=10, embedding_size=2, normalize_embeddings=False)\n loss_funcB = SphereFaceLoss(margin=margin, scale=scale, num_classes=10, embedding_size=2, normalize_embeddings=False)\n\n embedding_angles = torch.arange(0, 180)\n # multiply by 10 to make the embeddings unnormalized\n embeddings = torch.tensor(np.array([c_f.angle_to_coord(a) for a in embedding_angles])*10, requires_grad=True, dtype=torch.float) #2D embeddings\n labels = torch.randint(low=0, high=10, size=(180,))\n\n lossA = loss_funcA(embeddings, labels)\n lossB = loss_funcB(embeddings, labels)\n lossA.backward()\n lossB.backward()\n\n weightsA = loss_funcA.W\n weightsB = torch.nn.functional.normalize(loss_funcB.W, dim=0)\n\n product_of_magnitudesA = torch.norm(weightsA, p=2, dim=0).unsqueeze(0) * torch.norm(embeddings, p=2, dim=1).unsqueeze(1)\n product_of_magnitudesB = torch.norm(embeddings, p=2, dim=1).unsqueeze(1)\n cosinesA = torch.matmul(embeddings, weightsA) / (product_of_magnitudesA)\n cosinesB = torch.matmul(embeddings, weightsB) / (product_of_magnitudesB)\n coefficients = [scipy.special.binom(margin, 2*n) for n in range((margin // 2) + 1)]\n\n for i, j in enumerate(labels):\n curr_cosineA = cosinesA[i, j]\n curr_cosineB = cosinesB[i, j]\n cos_with_marginA = torch.zeros(len(coefficients))\n cos_with_marginB = torch.zeros(len(coefficients))\n for z, c in enumerate(coefficients):\n curr_valA = c*(curr_cosineA**(margin - (2*z)))*((1-curr_cosineA**2)**z)\n curr_valB = c*(curr_cosineB**(margin - (2*z)))*((1-curr_cosineB**2)**z)\n if z % 2 == 1:\n curr_valA *= -1\n curr_valB *= -1\n cos_with_marginA[z] = curr_valA\n cos_with_marginB[z] = curr_valB\n \n cos_with_marginA = torch.sum(cos_with_marginA)\n cos_with_marginB = torch.sum(cos_with_marginB)\n angleA = torch.acos(torch.clamp(curr_cosineA, -1 + 1e-7, 1 - 1e-7))\n angleB = torch.acos(torch.clamp(curr_cosineB, -1 + 1e-7, 1 - 1e-7))\n kA = (angleA / (math.pi / margin)).floor() # Equation 6: angles needs to be between [k*pi/m and (k+1)*pi/m]\n kB = (angleB / (math.pi / margin)).floor() # Equation 6: angles needs to be between [k*pi/m and (k+1)*pi/m]\n cosinesA[i, j] = ((-1)**kA)*cos_with_marginA - (2*kA)\n cosinesB[i, j] = ((-1)**kB)*cos_with_marginB - (2*kB)\n \n cosinesA *= product_of_magnitudesA\n cosinesB *= product_of_magnitudesB\n\n correct_lossA = torch.nn.functional.cross_entropy(cosinesA*scale, labels)\n correct_lossB = torch.nn.functional.cross_entropy(cosinesB*scale, labels)\n\n self.assertTrue(torch.isclose(lossA, correct_lossA))\n self.assertTrue(torch.isclose(lossB, correct_lossB))","sub_path":"tests/losses/test_large_margin_softmax_loss.py","file_name":"test_large_margin_softmax_loss.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"513818056","text":"'''\nThis program will print three form letters asking for votes in the past election.\nIt uses hardcoded tuples to insert into a constant letter format\n\nPranav Eranki - 10/1/2018\n'''\n\nUNCHANGING = \"Dear %s, \\nI would like you to vote for %s \\nbecause I think %s is best for \\nthis country. \\nSincerely, \\n%s\"\n\n# format = addressee, candidate, sender\nletter_1 = \"Steven\", \"Hillary Clinton\", \"Hillary Clinton\", \"Pranav\"\nletter_2 = \"Rahul\", \"Donald Trump\", \"Donald Trump\", \"Pranav\"\nletter_3 = \"Bhargav\", \"Bernie Sanders\", \"Bernie Sanders\", \"Pranav\"\n#Defining the array\nletters = [letter_1, letter_2, letter_3]\n\n#Prints the unchanging value with the letter values replaced in for the 'placeholders'\nfor letter in letters:\n print(UNCHANGING % letter)\n\n\n# For this code, the output is:\n\"\"\"\nDear Steven,\nI would like you to vote for Hillary Clinton\nbecause I think Hillary Clinton is best for\nthis country.\nSincerely,\nPranav\n\nDear Rahul,\nI would like you to vote for Donald Trump\nbecause I think Donald Trump is best for\nthis country.\nSincerely,\nPranav\n\nDear Bhargav,\nI would like you to vote for Bernie Sanders\nbecause I think Bernie Sanders is best for\nthis country.\nSincerely,\nPranav\n\"\"\"","sub_path":"assignment2_formletters.py","file_name":"assignment2_formletters.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"496114097","text":"# coding: utf-8\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom jedi.libs.db.store import db\nfrom jedi.libs.utils.dt import UTC_TZ\nfrom jedi.libs.utils.dt import localized_datetime\nfrom jedi.libs.utils.dt import datetime_to_timestamp\nfrom jedi.libs.utils.dt import timestamp_to_datetime\nfrom jedi.libs.cache.redis import mc\nfrom jedi.libs.cache.redis import cache\nfrom jedi.libs.cache.listed import ListCache\nfrom jedi.libs.sentry.client import client\n\nfrom jedi.models.props import Props\nfrom jedi.models.consts import ClassType\nfrom jedi.models.timeslot import Timeslot\nfrom jedi.models.timeslot.cached import CachedTimeslotNode\nfrom jedi.models.timeslot.cached import StudentCachedTimeslot\nfrom jedi.models.exception import LockError\nfrom jedi.models.exception import ClassStatusInfoError\nfrom jedi.models.exception import ClassStatusError, ClassTypeError\nfrom jedi.models.exception import TimeslotStatusError\nfrom jedi.models.exception import CachedTimeslotDuplicateError\n\nfrom .base import ClassBase\nfrom .consts import ClassStatus as Status\nfrom .consts import ClassStatusInfo as StatusInfo\nfrom .consts import ClassroomProvider as Provider\nfrom .consts import validate_reason\n\n_ONLINE_CLASS_CACHE_KEY_PREFIX = 'onlineclass:'\nONLINE_CLASS_CACHE_KEY = _ONLINE_CLASS_CACHE_KEY_PREFIX + 'id:%s'\nONLINE_CLASS_PB_CACHE_KEY = ONLINE_CLASS_CACHE_KEY + ':pb'\n\n_PB_ONLINE_CLASS_PREFIX = 'pb:oc:'\nPB_ONLINE_CLASS_LIST_BY_TEACHER = _PB_ONLINE_CLASS_PREFIX + 'list:by:teacher:{teacher_id}'\nPB_ONLINE_CLASS_LIST_BY_STUDENT = _PB_ONLINE_CLASS_PREFIX + 'list:by:student:{student_id}'\n\nMAX_UNDO_COUNT = 5 # change_finish_status_info max time\n\n\nclass OnlineClass(ClassBase):\n _tablename = 'onlineclass'\n\n PRODUCT = 'online_class'\n props = Props(product=PRODUCT)\n\n title = props.item('title', '')\n docs = props.item('docs', {'xuedianyun': [], 'duobeiyun': []})\n student_entering_time = props.item('student_entering_time', None)\n teacher_entering_time = props.item('teacher_entering_time', None)\n undo_count = props.item('undo_count', 0)\n _end_timestamp = props.item('_end_timestamp', None)\n\n @props.uuidgetter\n def uuid(self):\n return self.id\n\n @property\n def _start_timestamp(self):\n return self.schedule_timestamp\n\n def __init__(self, id, course_id, lesson_id, period,\n teacher_id, student_id, timeslot_id, schedule_timestamp,\n type, status, status_info, provider, create_time, update_time):\n self.id = str(id)\n self.course_id = str(course_id)\n self.lesson_id = str(lesson_id)\n self.period = int(period)\n self.teacher_id = str(teacher_id)\n self.student_id = str(student_id)\n self.timeslot_id = str(timeslot_id) if timeslot_id else None\n self.schedule_timestamp = int(schedule_timestamp)\n schedule_time = timestamp_to_datetime(schedule_timestamp)\n self.schedule_time = localized_datetime(schedule_time)\n self.type = ClassType(type)\n self.status = Status(status)\n self.status_info = StatusInfo(status_info)\n self.provider = Provider(provider)\n self.create_time = localized_datetime(create_time)\n self.update_time = localized_datetime(update_time)\n\n def __repr__(self):\n return '' % self.id\n\n @classmethod\n @cache(ONLINE_CLASS_CACHE_KEY % '{id}')\n def get(cls, id):\n sql = ('select id, course_id, lesson_id, period, teacher_id, student_id, timeslot_id, '\n 'schedule_timestamp, type, status, status_info, provider, create_time, update_time '\n 'from {table} where id=:id').format(table=cls._tablename)\n params = dict(id=id)\n r = db.execute(sql, params=params).fetchone()\n db.commit()\n return cls(*r) if r else None\n\n @classmethod\n def get_multi(cls, ids):\n cached = mc.get_multi([ONLINE_CLASS_CACHE_KEY % id for id in ids])\n return [cached.get(ONLINE_CLASS_CACHE_KEY % id) or\n cls.get(id) for id in ids]\n\n @classmethod\n def get_all_by_student_and_course_and_status(cls, student_id, course_id, status, start, limit):\n total, ids = cls.get_ids_by_student_and_course_and_status(\n student_id, course_id, status, start, limit)\n return total, cls.get_multi(ids)\n\n @classmethod\n def get_ids_by_student_and_course_and_status(cls, student_id, course_id, status, start, limit):\n ids = []\n info = cls._get_info_by_student(student_id, [], [status.value])\n for (id_, schedule_timestamp, cid, lid,\n type_, status_value, status_info_, provider_, _) in info:\n if str(cid) == str(course_id) and (int(status_value) == int(status.value)):\n ids.append(str(id_))\n total = len(ids)\n return total, ids[start: start + limit]\n\n @classmethod\n def get_last_scheduled_class_id(cls, student_id, course_id):\n sql = ('select id from {table} '\n 'where student_id=:student_id and course_id=:course_id '\n 'and status=:status and status_info=:status_info '\n 'order by schedule_timestamp desc limit 1').format(table=cls._tablename)\n params = dict(\n student_id=student_id,\n course_id=course_id,\n status=Status.finished.value,\n status_info=StatusInfo.finished_as_as_scheduled.value\n )\n r = db.execute(sql, params).fetchone()\n db.commit()\n if r:\n return str(r[0])\n\n @classmethod\n def gets_by_student_and_lesson_and_status(cls, student_id, lesson_id, status, start, limit):\n total, ids = cls.get_ids_by_student_and_lesson_and_status(\n student_id, lesson_id, status, start, limit)\n return total, cls.get_multi(ids)\n\n @classmethod\n def gets_by_time_with_fitler(cls, start_timestamp, end_timestamp, start, limit,\n teacher_id=None, student_id=None,\n types=[], statuses=[], status_infos=[],\n providers=[], course_ids=[]):\n rs = cls._get_info_by_time_with_filter(\n start_timestamp,\n end_timestamp,\n teacher_id=teacher_id,\n student_id=student_id,\n types=types,\n statuses=statuses,\n status_infos=status_infos,\n providers=providers,\n course_ids=course_ids\n )\n ids = [str(r[0]) for r in rs]\n return len(ids), cls.get_multi(ids[start:start + limit])\n\n @classmethod\n def gets_by_students_with_filter(cls, start_timestamp, end_timestamp, start, limit,\n student_ids, teacher_id=None,\n types=[], statuses=[], status_infos=[],\n providers=[], course_ids=[]):\n if not student_ids:\n raise ValueError\n rs = cls._get_info_by_time_with_filter(\n start_timestamp,\n end_timestamp,\n teacher_id=teacher_id,\n types=types,\n statuses=statuses,\n status_infos=status_infos,\n providers=providers,\n course_ids=course_ids\n )\n ids = [str(r[0]) for r in rs if str(r[8]) in student_ids]\n return len(ids), cls.get_multi(ids[start:start + limit])\n\n @classmethod\n def _get_info_by_time_with_filter(\n cls, start_timestamp, end_timestamp,\n teacher_id=None, student_id=None,\n types=[], statuses=[],\n status_infos=[], providers=[],\n course_ids=[]):\n rs = cls._get_info_by_time(start_timestamp, end_timestamp, teacher_id, student_id)\n return cls._online_class_filter(\n rs, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n @classmethod\n def _get_info_by_time(cls, start_timestamp, end_timestamp, teacher_id=None, student_id=None):\n student_id_sql = 'student_id=:student_id and ' if student_id else ''\n teacher_id_sql = 'teacher_id=:teacher_id and ' if teacher_id else ''\n\n sql = ('select id, schedule_timestamp, course_id, lesson_id, type, '\n 'status, status_info, provider, student_id from {table} '\n 'where ' + student_id_sql + teacher_id_sql +\n 'schedule_timestamp >= :start_timestamp '\n 'and schedule_timestamp < :end_timestamp '\n 'order by schedule_timestamp desc'\n ).format(table=cls._tablename)\n params = dict(\n start_timestamp=start_timestamp,\n end_timestamp=end_timestamp,\n teacher_id=teacher_id,\n student_id=student_id\n )\n rs = db.execute(sql, params).fetchall()\n db.commit()\n return rs\n\n @classmethod\n def get_ids_by_student_and_lesson_and_status(cls, student_id, lesson_id, status, start, limit):\n ids = []\n info = cls._get_info_by_student(student_id, [], [status.value])\n for (id_, schedule_timestamp, cid, lid,\n type_, status_value, status_info_, provider_, _) in info:\n if str(lid) == str(lesson_id) and (int(status_value) == int(status.value)):\n ids.append(str(id_))\n total = len(ids)\n return total, ids[start: start + limit]\n\n @classmethod\n def gets_by_student_with_filter(\n cls, student_id, start, limit, types=[], statuses=[],\n status_infos=[], providers=[], start_timestamp=None,\n end_timestamp=None, course_ids=[]):\n\n rs = cls.get_info_by_student_with_filter(\n student_id, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n if start_timestamp:\n rs = [r for r in rs if r[1] >= start_timestamp]\n if end_timestamp:\n rs = [r for r in rs if r[1] < end_timestamp]\n ids = [str(r[0]) for r in rs]\n total = len(ids)\n return total, cls.get_multi(ids[start: start + limit])\n\n @classmethod\n def gets_by_teacher_with_filter(\n cls, teacher_id, start, limit, types=[], statuses=[],\n status_infos=[], providers=[], start_timestamp=None,\n end_timestamp=None, course_ids=[]):\n\n rs = cls.get_info_by_teacher_with_filter(\n teacher_id, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n if start_timestamp:\n rs = [r for r in rs if r[1] >= start_timestamp]\n if end_timestamp:\n rs = [r for r in rs if r[1] < end_timestamp]\n ids = [str(r[0]) for r in rs]\n total = len(ids)\n return total, cls.get_multi(ids[start: start + limit])\n\n @classmethod\n def get_info_by_student_with_filter(\n cls, student_id, types=[], statuses=[],\n status_infos=[], providers=[], course_ids=[]):\n rs = cls._get_info_by_student(student_id, types, statuses)\n return cls._online_class_filter(\n rs, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n @classmethod\n def get_info_by_teacher_with_filter(\n cls, teacher_id, types=[], statuses=[],\n status_infos=[], providers=[], course_ids=[]):\n rs = cls._get_info_by_teacher(teacher_id, types, statuses)\n return cls._online_class_filter(\n rs, types=types, statuses=statuses, status_infos=status_infos,\n providers=providers, course_ids=course_ids)\n\n @classmethod\n def _online_class_filter(\n cls, rs, types=[], statuses=[], status_infos=[],\n providers=[], course_ids=[]):\n t = []\n if not types and not statuses and not status_infos and not providers and not course_ids:\n return rs\n # 这块逻辑有点复杂, status or status_info,但是 status_info 不能把其他的 status 给过滤掉\n status_infos_statuses = set()\n for status_info in status_infos:\n status_infos_statuses.add(StatusInfo.get_status_from_status_info(status_info))\n statuses = set(statuses) - status_infos_statuses\n for r in rs:\n (id_, schedule_timestamp, course_id_, lesson_id,\n type_, status_, status_info_, provider_, student_id) = r\n if statuses and status_infos:\n if (status_ not in statuses and status_info_ not in status_infos):\n continue\n elif statuses:\n if status_ not in statuses:\n continue\n elif status_infos:\n if status_info_ not in status_infos:\n continue\n if providers and provider_ not in providers:\n continue\n if course_ids and int(course_id_) not in course_ids:\n continue\n if types and type_ not in types:\n continue\n\n t.append(r)\n return t\n\n @classmethod\n def _get_info_by_student(cls, student_id, types, statuses):\n type_sql = ''\n status_sql = ''\n\n if types:\n type_sql = 'and ' + cls.build_args('type', types) + ' '\n\n if statuses:\n status_sql = 'and ' + cls.build_args('status', statuses) + ' '\n\n sql = ('select id, schedule_timestamp, course_id, lesson_id, type, '\n 'status, status_info, provider, student_id from {table} '\n 'where student_id=:student_id '\n '{type_sql}'\n '{status_sql}'\n ).format(table=cls._tablename,\n type_sql=type_sql,\n status_sql=status_sql)\n params = dict(student_id=student_id)\n rs = db.execute(sql, params).fetchall()\n rs = sorted(rs, key=lambda x: -x[1])\n db.commit()\n return rs\n\n @classmethod\n def build_args(cls, name, args):\n args = [str(arg) for arg in args]\n return '%s in (%s)' % (name, ','.join(args))\n\n @classmethod\n def _get_info_by_teacher(cls, teacher_id, types, statuses):\n type_sql = ''\n status_sql = ''\n\n if types:\n type_sql = 'and ' + cls.build_args('type', types) + ' '\n\n if statuses:\n status_sql = 'and ' + cls.build_args('status', statuses) + ' '\n\n sql = ('select id, schedule_timestamp, course_id, lesson_id, type, '\n 'status, status_info, provider, student_id from {table} '\n 'where teacher_id=:teacher_id '\n '{type_sql}'\n '{status_sql}'\n ).format(table=cls._tablename,\n type_sql=type_sql,\n status_sql=status_sql)\n params = dict(teacher_id=teacher_id)\n rs = db.execute(sql, params).fetchall()\n db.commit()\n rs = sorted(rs, key=lambda x: -x[1])\n return rs\n\n @classmethod\n def add(cls, course_id, lesson_id, student_id, timeslot_id, period, provider, type):\n if type in (ClassType.none, ClassType.open_class):\n raise ClassTypeError('class type does not match!')\n\n timeslot = Timeslot.get(timeslot_id)\n if not timeslot.can_be_booked():\n raise TimeslotStatusError\n\n if timeslot.type != ClassType.none and timeslot.type != type:\n raise ClassTypeError('class type does not match')\n\n timeslot.locker.aquire()\n try:\n student_timeslot = StudentCachedTimeslot.get(student_id)\n\n node = CachedTimeslotNode(\n timeslot.start_timestamp,\n timeslot.end_timestamp)\n\n if student_timeslot.exist(node):\n raise CachedTimeslotDuplicateError\n\n sql = ('insert into {table} (course_id, lesson_id, period, '\n 'teacher_id, student_id, timeslot_id, '\n 'schedule_timestamp, type, status, status_info, provider ) '\n 'values (:course_id, :lesson_id, :period, :teacher_id, '\n ':student_id, :timeslot_id, '\n ':schedule_timestamp, :type, :status, :status_info, :provider '\n ')').format(table=cls._tablename)\n\n params = dict(\n course_id=course_id,\n lesson_id=lesson_id,\n period=period,\n teacher_id=timeslot.user_id,\n student_id=student_id,\n timeslot_id=timeslot_id,\n schedule_timestamp=timeslot.start_timestamp,\n type=type.value,\n status=Status.created.value,\n status_info=StatusInfo.none.value,\n provider=provider.value,\n )\n\n r = db.execute(sql, params=params)\n\n if r.lastrowid:\n try:\n student_timeslot.insert(node)\n except (CachedTimeslotDuplicateError, LockError):\n db.rollback()\n raise\n id = str(r.lastrowid)\n db.commit()\n oc = cls.get(id)\n timeslot.bind(oc)\n oc._end_timestamp = timeslot.end_timestamp\n return oc\n db.rollback()\n finally:\n timeslot.locker.release()\n\n def _change_teacher_or_student_check(self, status_info, **kwargs):\n scheduler = kwargs.get('scheduler')\n if not scheduler:\n raise Exception('need scheduler')\n status = StatusInfo.get_status_from_status_info(status_info)\n now = datetime.now(tz=UTC_TZ)\n if self.schedule_time > now:\n if status != Status.canceled:\n raise ClassStatusInfoError\n if not self.can_be_canceled():\n raise ClassStatusError('can not cancel IN_CLASS class')\n else:\n if status != Status.finished:\n raise ClassStatusInfoError\n if not self.can_be_finished():\n raise ClassStatusError('Only IN_CLASS class can be finished')\n self._check_end_class_reason(status_info)\n return scheduler, status\n\n def change_teacher(self, timeslot_id, status_info, **kwargs):\n scheduler, status = self._change_teacher_or_student_check(status_info, **kwargs)\n if not status_info.is_change_teacher_reason():\n raise ClassStatusInfoError\n return self._change_teacher(timeslot_id, status, status_info, scheduler)\n\n def _change_teacher(self, timeslot_id, status, status_info, scheduler):\n timeslot = Timeslot.get(timeslot_id)\n timeslot.locker.aquire()\n try:\n if not timeslot.can_be_booked():\n raise TimeslotStatusError\n if timeslot.type != ClassType.none and timeslot.type != self.type:\n raise ClassTypeError('class type does not match')\n # cancel or finish old onlineclass\n update_oc_sql = ('update {table} set status=:status, status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n update_oc_params = dict(status=status.value,\n status_info=status_info.value,\n id=self.id)\n db.execute(update_oc_sql, params=update_oc_params)\n # add new onlineclass\n add_sql = ('insert into {table} (course_id, lesson_id, period, teacher_id, '\n 'student_id, timeslot_id, schedule_timestamp, type, '\n 'status, status_info, provider ) values '\n '(:course_id, :lesson_id, :period, :teacher_id, :student_id, :timeslot_id, '\n ':schedule_timestamp, :type, :status, :status_info, :provider '\n ')').format(table=self._tablename)\n\n add_params = dict(\n course_id=self.course_id,\n lesson_id=self.lesson_id,\n period=self.period,\n teacher_id=timeslot.user_id,\n student_id=self.student_id,\n timeslot_id=timeslot.id,\n schedule_timestamp=timeslot.start_timestamp,\n type=self.type.value,\n status=self.status.value,\n status_info=self.status_info.value,\n provider=self.provider.value,\n )\n r = db.execute(add_sql, params=add_params)\n\n if r.lastrowid:\n id = str(r.lastrowid)\n db.commit()\n # bind new timeslot\n oc = self.get(id)\n timeslot.bind(oc)\n # available old timeslot\n self._update_timeslot_status_by_status_changed(status_info, scheduler)\n oc._end_timestamp = timeslot.end_timestamp\n self.clear_cache()\n # to clear pb cache\n oc.clear_cache()\n return oc\n\n db.rollback()\n finally:\n timeslot.locker.release()\n\n def change_student(self, student_id, status_info, **kwargs):\n scheduler, status = self._change_teacher_or_student_check(status_info, **kwargs)\n if not status_info.is_change_student_reason():\n raise ClassStatusInfoError\n return self._change_student(student_id, status, status_info)\n\n def _change_student(self, student_id, status, status_info):\n self.teacher_timeslot.locker.aquire()\n try:\n new_student_timeslot = StudentCachedTimeslot.get(student_id)\n node = CachedTimeslotNode(self._start_timestamp, self._end_timestamp)\n if new_student_timeslot.exist(node):\n raise CachedTimeslotDuplicateError\n\n # cancel or finish old onlineclass\n update_oc_sql = ('update {table} set status=:status, status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n update_oc_params = dict(status=status.value,\n status_info=status_info.value,\n id=self.id)\n db.execute(update_oc_sql, params=update_oc_params)\n # add new onlineclass\n add_sql = ('insert into {table} (course_id, lesson_id, period, teacher_id, '\n 'student_id, timeslot_id, schedule_timestamp, type, '\n 'status, status_info, provider ) values '\n '(:course_id, :lesson_id, :period, :teacher_id, :student_id, :timeslot_id, '\n ':schedule_timestamp, :type, :status, :status_info, :provider '\n ')').format(table=self._tablename)\n\n add_params = dict(\n course_id=self.course_id,\n lesson_id=self.lesson_id,\n period=self.period,\n teacher_id=self.teacher_id,\n student_id=student_id,\n timeslot_id=self.timeslot_id,\n schedule_timestamp=self.schedule_timestamp,\n type=self.type.value,\n status=self.status.value,\n status_info=self.status_info.value,\n provider=self.provider.value,\n )\n r = db.execute(add_sql, params=add_params)\n\n if r.lastrowid:\n try:\n new_student_timeslot.insert(node)\n except (CachedTimeslotDuplicateError, LockError):\n db.rollback()\n raise\n id = str(r.lastrowid)\n db.commit()\n # bind timeslot to new onlineclass\n oc = self.get(id)\n #\n self.teacher_timeslot.force_bind(oc)\n # remove old student timeslot\n self._remove_student_timeslot()\n self.clear_cache()\n # to clear pb cache\n oc._end_timestamp = self.teacher_timeslot.end_timestamp\n oc.clear_cache()\n return oc\n\n db.rollback()\n finally:\n self.teacher_timeslot.locker.release()\n\n @classmethod\n def get_booked_classes_by_lesson(cls, lesson_id):\n sql = ('select id from {table} '\n 'where lesson_id=:lesson_id '\n 'and status in (:created, :ready) '\n 'and schedule_timestamp > :now_ts '\n 'order by schedule_timestamp'\n ).format(table=cls._tablename)\n\n now_ts = datetime_to_timestamp(datetime.now(UTC_TZ))\n params = dict(\n lesson_id=lesson_id,\n now_ts=now_ts,\n created=Status.created.value,\n ready=Status.ready.value\n )\n\n rs = db.execute(sql, params=params).fetchall()\n db.commit()\n ids = [str(r[0]) for r in rs]\n return [cls.get(id_) for id_ in ids]\n\n def get_student_class_hour(self, **kwargs):\n return self.period\n\n def change_provider(self, provider):\n sql = ('update {table} set provider=:provider '\n 'where id=:id').format(table=self._tablename)\n params = dict(provider=provider.value, id=self.id)\n db.execute(sql, params=params)\n db.commit()\n self.clear_cache()\n\n def change_finish_status_info(self, status_info, scheduler):\n if not scheduler:\n raise Exception('need scheduler')\n self._check_change_finish_status_info(status_info)\n # NOTE: this feature is stupid\n validate_reason(self.status, status_info)\n sql = ('update {table} set status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n params = dict(status_info=status_info.value, id=self.id)\n db.execute(sql, params=params)\n db.commit()\n self.undo_count = self.undo_count + 1\n self.clear_cache()\n\n def bind(self, lesson_id):\n sql = ('update {table} set lesson_id=:lesson_id '\n 'where id=:id').format(table=self._tablename)\n params = dict(lesson_id=lesson_id, id=self.id)\n db.execute(sql, params=params)\n db.commit()\n self.clear_cache()\n\n def enroll(self, student_id, **kwargs):\n pass\n\n def has_enrolled(self, student_id):\n return student_id == self.student_id\n\n def is_canceled(self):\n return self.status == Status.canceled\n\n def is_finished(self):\n return self.status == Status.finished\n\n def to_ready(self):\n if self.status == Status.created:\n self._change_status(Status.ready)\n\n def is_ready(self):\n return self.status == Status.ready\n\n def can_be_canceled(self):\n if self.is_finished():\n return False\n if self.is_canceled():\n return False\n if not self.teacher_timeslot:\n return False\n start_ts = self.teacher_timeslot.start_timestamp\n now_ts = datetime_to_timestamp(datetime.now(tz=UTC_TZ))\n return start_ts > now_ts\n\n def can_be_finished(self):\n if self.is_canceled():\n return False\n if self.is_finished() and self.status_info != StatusInfo.finished_as_tmp:\n return False\n if not self.teacher_timeslot:\n return False\n start_ts = self.teacher_timeslot.start_timestamp\n now_ts = datetime_to_timestamp(datetime.now(tz=UTC_TZ))\n return start_ts <= now_ts\n\n def to_canceled(self, reason, **kwargs):\n scheduler = kwargs.get('scheduler')\n if not scheduler:\n raise Exception('need scheduler')\n _status = StatusInfo.get_status_from_status_info(reason)\n if _status != Status.canceled:\n raise ValueError('bad reason')\n if not self.can_be_canceled():\n raise ClassStatusError('can not cancel IN_CLASS class')\n self._change_status(Status.canceled, reason)\n self._update_timeslot_status_by_status_changed(reason, scheduler)\n self._remove_student_timeslot()\n\n def cancel_and_lock_timeslot(self, scheduler):\n \"\"\"Change student without new student will cancel class and lock timeslot\"\"\"\n if not self.can_be_canceled():\n raise ClassStatusError('can not cancel IN_CLASS class')\n now = datetime.now(tz=UTC_TZ)\n if self.schedule_time > now + timedelta(hours=24):\n reason = StatusInfo.canceled_student_no_deduction\n else:\n reason = StatusInfo.canceled_student_deduction\n self._change_status(Status.canceled, reason)\n self.teacher_timeslot.force_lock(scheduler)\n self._remove_student_timeslot()\n\n def update_user_entering_classroom_time(self, user_id, entering_ts):\n if str(user_id) == self.student_id:\n self.student_entering_time = int(entering_ts)\n self.clear_cache()\n elif str(user_id) == self.teacher_id:\n self.teacher_entering_time = int(entering_ts)\n self.clear_cache()\n else:\n raise ValueError('Cannot find user id in this class')\n\n def _remove_student_timeslot(self):\n student_timeslot = StudentCachedTimeslot.get(self.student_id)\n if self._start_timestamp and self._end_timestamp:\n node = CachedTimeslotNode(\n self._start_timestamp, self._end_timestamp)\n student_timeslot.remove(node)\n else:\n student_timeslot._clear_cache()\n\n def to_finished(self, reason, scheduler=None):\n from .mq import set_life_cycle_to_trial_finished_mq\n\n _status = StatusInfo.get_status_from_status_info(reason)\n if _status != Status.finished:\n raise ValueError('bad reason')\n if not scheduler:\n raise Exception('need scheduler')\n if not self.can_be_finished():\n raise ClassStatusError('Only IN_CLASS class can be finished')\n self._change_status(Status.finished, reason)\n self._update_timeslot_status_by_status_changed(reason, scheduler)\n self._remove_student_timeslot()\n job_body = '{id}:{type}'.format(id=self.id, type=self.type.value)\n try:\n set_life_cycle_to_trial_finished_mq.put(job_body)\n except Exception as e:\n extra = dict(error=str(e))\n client.captureMessage(\n 'set_life_cycle_to_trial_finished_mq error job_body=%s' % job_body, extra=extra)\n pass\n\n def _change_status(self, status, status_info=None):\n if status_info is None:\n status_info = StatusInfo.none\n validate_reason(status, status_info)\n if status in (Status.canceled, Status.finished):\n self._check_end_class_reason(status_info)\n sql = ('update {table} set status=:status, status_info=:status_info '\n 'where id=:id').format(table=self._tablename)\n params = dict(status=status.value, id=self.id)\n params['status_info'] = status_info.value\n db.execute(sql, params=params)\n db.commit()\n self.clear_cache()\n\n def _check_end_class_reason(self, status_info):\n now_ts = datetime_to_timestamp(datetime.now(UTC_TZ))\n if self.schedule_timestamp - now_ts >= 24 * 60 * 60:\n if not status_info.is_out_24H_reason():\n raise ClassStatusError('%s is not valid out 24H reason' % status_info.name)\n elif self.schedule_timestamp - now_ts >= 2 * 60 * 60:\n if not status_info.is_in_24H_reason():\n raise ClassStatusError('%s is not valid in 24H reason' % status_info.name)\n elif self.schedule_timestamp > now_ts:\n if not status_info.is_in_2H_reason():\n raise ClassStatusError('%s is not valid in 2H reason' % status_info.name)\n elif self.schedule_timestamp <= now_ts < self._end_timestamp:\n if not status_info.is_in_class_reason():\n raise ClassStatusError('%s is not valid in class reason' % status_info.name)\n else:\n if not status_info.is_after_class_reason():\n raise ClassStatusError('%s is not valid after class reason' % status_info.name)\n\n def _update_timeslot_status_by_status_changed(self, status_info, operator_id):\n if not self.teacher_timeslot:\n return\n if status_info.need_release_timeslot():\n self.teacher_timeslot.to_available(operator_id)\n elif status_info.need_cancel_timeslot():\n self.teacher_timeslot.to_canceled(operator_id)\n elif status_info.need_finish_timeslot():\n self.teacher_timeslot.to_finished(operator_id)\n\n def _check_change_finish_status_info(self, status_info):\n if self.undo_count >= MAX_UNDO_COUNT:\n raise ClassStatusError('cannot change finish status info more than 5 times')\n if self.status_info == StatusInfo.finished_as_tmp:\n raise ClassStatusError('finished_as_tmp cannot change status info')\n if status_info == StatusInfo.finished_as_tmp:\n raise ClassStatusError('cannot change back to finished_as_tmp')\n if self.status != Status.finished:\n raise ClassStatusError('not in finish status')\n if StatusInfo.get_status_from_status_info(status_info) != Status.finished:\n raise ClassStatusError('not in finish status')\n if status_info == StatusInfo.finished_as_as_scheduled:\n raise ClassStatusError('cannot change to finished_as_as_scheduled')\n if self.status_info == status_info:\n raise ClassStatusError('cannot change to same status info')\n now_ts = datetime_to_timestamp(datetime.now(tz=UTC_TZ))\n if self.schedule_timestamp + 7 * 24 * 60 * 60 < now_ts:\n raise ClassStatusError('cannot change status info after one week')\n\n def clear_pb_cache(self):\n mc.delete(ONLINE_CLASS_PB_CACHE_KEY % self.id)\n\n def clear_cache(self):\n mc.delete(ONLINE_CLASS_CACHE_KEY % self.id)\n ListCache(PB_ONLINE_CLASS_LIST_BY_TEACHER.format(teacher_id=self.teacher_id)).clear()\n ListCache(PB_ONLINE_CLASS_LIST_BY_STUDENT.format(student_id=self.student_id)).clear()\n self.clear_pb_cache()\n","sub_path":"jedi/jedi/models/onlineclass/onlineclass.py","file_name":"onlineclass.py","file_ext":"py","file_size_in_byte":34134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"616759718","text":"from django.conf.urls import url, include\nfrom . import views\n\napp_name = 'employees'\n\nurlpatterns = [\n\n url(r'^$', views.index, name='home'),\n url(r'^create/$', views.EmployeeCRUD.create, name='create'),\n url(r'^edit/(?P\\d+)/$', views.EmployeeCRUD.edit_employee, name='edit-employee'),\n url(r'^update/(?P\\d+)/$', views.EmployeeCRUD.update, name='update'),\n url(r'^delete/(?P\\d+)/$', views.EmployeeCRUD.delete, name='delete'),\n]\n","sub_path":"apps/employees/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"219966036","text":"## Assignment 3 Solution\r\n# 3-Implement following sorting Algorithms Programmatically as well astheoretically:\r\n# \tA)\tBubble Sort.\r\n#\tB)\tQuick Sort.\r\n# \tC)\tSelection Sort.\r\n# \tD)\tMerge Sort.\r\n \r\n# NOTE* You have to submit a Document file along with your code file which contains explanation \r\n# of these Sorting Algorithms with images. Also you have to mention the Time Complexity \r\n# of each Sorting Algorithms.\r\n\r\n# Bubble sort\r\n# Worst Case Complexity O(n^2)\r\ndef bubble_sort(List):\r\n\tn = len(List)\r\n\r\n\tfor i in range(n):\r\n\t\tfor j in range(n-i-1):\r\n\t\t\tif List[j] > List[j+1]:\r\n\t\t\t\tList[j], List[j+1] = List[j+1], List[j]\r\n\t\tprint(\"After pass\",(i+1),\" :\", List)\r\n\r\n\r\n# Quick Sort\r\n# Worst Case Complexity O(n^2)\r\ndef quick_sort(List):\r\n\tdef partition(start, end):\r\n\t\tx = List[end-1]\r\n\t\ti = start - 1\r\n\r\n\t\tfor j in range(start, end-1):\r\n\t\t\tif List[j] <= x:\r\n\t\t\t\ti += 1\r\n\t\t\t\tList[i], List[j] = List[j], List[i]\r\n\r\n\t\tList[i+1], List[end-1] = List[end-1], List[i+1]\r\n\r\n\t\treturn i+1\r\n\r\n\tdef quick_sort_sub(start, end):\r\n\t\tif start < end:\r\n\t\t\tpartition_index = partition(start, end)\r\n\t\t\tquick_sort_sub(start, partition_index)\r\n\t\t\tquick_sort_sub(partition_index + 1, end)\r\n\r\n\tquick_sort_sub(0, len(List))\r\n\r\n\r\n# Selection Sort\r\n# Worst Case Complexity O(n^2)\r\ndef selection_sort(List):\r\n\tdef arg_min(i):\r\n\t\tmin_item, min_index = float('inf'), None\r\n\t\tfor j in range(i, len(List)):\r\n\t\t\tif List[j] < min_item:\r\n\t\t\t\tmin_item = List[j]\r\n\t\t\t\tmin_index = j\r\n\t\treturn min_index\r\n\r\n\t# Main sorting loop\r\n\tfor i in range(len(List)-1):\r\n\t\t# Find min element in unsorted part\r\n\t\tmin_index = arg_min(i)\r\n\r\n\t\t# Append the min_item to unsorted part\r\n\t\tList[i], List[min_index] = List[min_index], List[i]\r\n\r\n\r\n# Merge Sort\r\n# Worst Case Complexity O(n log n) \r\ndef merge_sort(List):\r\n\t# Function to sort two sorted sub arrays\r\n\tdef merge(l1, l2):\r\n\t\tl3 = []\r\n\t\ti = j = 0\r\n\r\n\t\twhile i None:\n \"\"\"\n Base class for audio providers.\n\n ### Arguments\n - output_directory: The directory to save the downloaded songs to.\n - output_format: The format to save the downloaded songs in.\n - cookie_file: The path to a file containing cookies to be used by YTDL.\n - search_query: The query to use when searching for songs.\n - filter_results: Whether to filter results.\n\n ### Errors\n - raises `NotImplementedError` if self.name is not set.\n \"\"\"\n\n self.output_format = output_format\n self.cookie_file = cookie_file\n self.search_query = search_query\n self.filter_results = filter_results\n\n if self.output_format == \"m4a\":\n ytdl_format = \"bestaudio[ext=m4a]/bestaudio/best\"\n elif self.output_format == \"opus\":\n ytdl_format = \"bestaudio[ext=webm]/bestaudio/best\"\n else:\n ytdl_format = \"bestaudio\"\n\n self.audio_handler = YoutubeDL(\n {\n \"format\": ytdl_format,\n \"quiet\": True,\n \"no_warnings\": True,\n \"encoding\": \"UTF-8\",\n \"logger\": YTDLLogger(),\n \"cookiefile\": self.cookie_file,\n \"outtmpl\": f\"{get_temp_path()}/%(id)s.%(ext)s\",\n \"retries\": 5,\n }\n )\n\n def search(self, song: Song) -> Optional[str]:\n \"\"\"\n Search for a song and return best match.\n\n ### Arguments\n - song: The song to search for.\n\n ### Returns\n - The url of the best match or None if no match was found.\n \"\"\"\n\n raise NotImplementedError\n\n def get_results(self, search_term: str, **kwargs):\n \"\"\"\n Get results from audio provider.\n\n ### Arguments\n - search_term: The search term to use.\n - kwargs: Additional arguments.\n\n ### Returns\n - A list of results.\n \"\"\"\n\n raise NotImplementedError\n\n def order_results(self, results, song: Song):\n \"\"\"\n Order results.\n\n ### Arguments\n - results: The results to order.\n - song: The song to order for.\n\n ### Returns\n - The ordered results.\n \"\"\"\n\n raise NotImplementedError\n\n def get_download_metadata(self, url: str, download: bool = False) -> Dict:\n \"\"\"\n Get metadata for a download using yt-dlp.\n\n ### Arguments\n - url: The url to get metadata for.\n\n ### Returns\n - A dictionary containing the metadata.\n \"\"\"\n\n try:\n\n data = self.audio_handler.extract_info(url, download=download)\n\n if data:\n return data\n except Exception as exception:\n raise AudioProviderError(f\"YT-DLP download error - {url}\") from exception\n\n raise AudioProviderError(f\"No metadata found for the provided url {url}\")\n\n @property\n def name(self) -> str:\n \"\"\"\n Get the name of the provider.\n\n ### Returns\n - The name of the provider.\n \"\"\"\n\n return self.__class__.__name__\n","sub_path":"spotdl/providers/audio/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"97084175","text":"import base64\nfrom functools import wraps\n\nfrom flask import Response, request\n\nfrom app.config import Config\n\n\ndef check(authorization_header):\n encoded = authorization_header.split()[-1]\n auth = Config.BASIC_AUTH_USER + \":\" + Config.BASIC_AUTH_PASSWORD\n if encoded == base64.b64encode(auth.encode(\"utf-8\")).decode(\"utf-8\"):\n return True\n\n\ndef basic_auth_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n try:\n authorization_header = request.headers.get('Authorization')\n if authorization_header and check(authorization_header):\n return f(*args, **kwargs)\n else:\n resp = Response()\n resp.headers['WWW-Authenticate'] = 'Basic'\n return resp, 401\n except Exception as e:\n raise e\n\n return decorated\n","sub_path":"app/middlewares/basic_authenticate.py","file_name":"basic_authenticate.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"317404821","text":"# import numpy as np\n\ndef main():\n\n arr = [35, 3, 5, 1, 10, 7, -3, 4]\n # arr = np.random.rand(200)\n arr = simple_sort(arr)\n \n print(arr)\n\ndef simple_sort(arr):\n checked_pos = 0\n length = len(arr)\n\n for i in range(length):\n # 対象とする範囲内での最小値を求める\n m = arr[i]\n min_pos = i\n for j in range(i, length):\n if arr[j] < m:\n m = arr[j]\n min_pos = j\n # print(arr, m, min_pos)\n # 入れ替える\n tmp = arr[i]\n arr[i] = arr[min_pos]\n arr[min_pos] = tmp\n \n return arr\n\nif __name__ == \"__main__\":\n main()","sub_path":"simple_sort.py","file_name":"simple_sort.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"464174392","text":"# -*- coding: utf-8 -*-\n\"\"\"Application forms.\"\"\"\n\nfrom datetime import date\n\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.file import FileAllowed, FileField, FileRequired\nfrom pycountry import countries\nfrom wtforms import (BooleanField, Field, SelectField, SelectMultipleField, StringField,\n SubmitField, TextField, validators)\nfrom wtforms.fields.html5 import DateField, EmailField, URLField\nfrom wtforms.validators import UUID, DataRequired, Email, Regexp, Required, ValidationError, url\nfrom wtforms.widgets import HTMLString, TextArea, html_params\n\nfrom . import models\nfrom .config import DEFAULT_COUNTRY\n\n\ndef validate_orcid_id_field(form, field):\n \"\"\"Validate ORCID iD.\"\"\"\n if not field.data:\n return\n try:\n models.validate_orcid_id(field.data)\n except ValueError as ex:\n raise ValidationError(str(ex))\n\n\nclass PartialDate:\n \"\"\"Widget for a partical date with 3 selectors (year, month, day).\"\"\"\n\n __current_year = date.today().year\n\n def __call__(self, field, **kwargs):\n \"\"\"Render widget.\"\"\"\n kwargs.setdefault('id', field.id)\n html = [\"\" % (field.data, ), '' % html_params(**kwargs)]\n html.extend(self.render_select(\"year\", field))\n html.extend(self.render_select(\"month\", field))\n html.extend(self.render_select(\"day\", field))\n html.append(\"
\")\n return HTMLString(''.join(html))\n\n @classmethod\n def render_select(cls, part, field):\n \"\"\"Render select for a specific part of date.\"\"\"\n yield \"\" % html_params(name=field.name + \":\" + part)\n # If user didn't specifiy the date then the year range will start from current year + 5 years\n range_value = cls.__current_year + 5\n try:\n current_value = int(getattr(field.data, part))\n range_value = current_value + 5\n except Exception:\n current_value = None\n # TODO: localization\n yield \"%s \" % (html_params(value=\"\", selected=(current_value is None)),\n part.capitalize())\n option_format = \"%04d \" if part == \"year\" else \"%02d \"\n for v in range(range_value, 1912, -1) if part == \"year\" else range(\n 1, 13 if part == \"month\" else 32):\n yield option_format % (html_params(value=v, selected=(v == current_value)), v)\n yield \" \"\n\n\nclass PartialDateField(Field):\n \"\"\"Partial date field.\"\"\"\n\n widget = PartialDate()\n\n def process(self, formdata, data=None):\n \"\"\"Process incoming data, calling process_data.\"\"\"\n self.process_errors = []\n if data is None:\n data = self.default or models.PartialDate()\n\n # self.object_data = data\n self.data = data\n\n if formdata is not None:\n new_data = {}\n for f in (\n \"year\",\n \"month\",\n \"day\",\n ):\n try:\n if (self.name + \":\" + f) in formdata:\n raw_val = formdata.get(self.name + \":\" + f)\n value = int(raw_val) if raw_val else None\n else:\n value = getattr(self.data, f)\n new_data[f] = value\n except ValueError as e:\n new_data[f] = None\n self.process_errors.append(e.args[0])\n self.data = models.PartialDate(**new_data)\n try:\n for filter in self.filters:\n self.data = filter(self.data)\n except ValueError as e:\n self.process_errors.append(e.args[0])\n\n\nclass CountrySelectField(SelectField):\n \"\"\"Country dropdown widget.\"\"\"\n\n # Order the countly list by the name and add a default (Null) value\n country_choices = [(c.alpha_2, c.name) for c in countries]\n country_choices.sort(key=lambda e: e[1])\n country_choices.insert(0, (\"\", \"Country\"))\n\n def __init__(self, *args, **kwargs):\n \"\"\"Set up the value list.\"\"\"\n if len(args) == 0 and \"label\" not in kwargs:\n kwargs[\"label\"] = \"Country\"\n super().__init__(*args, choices=self.country_choices, **kwargs)\n\n\nclass BitmapMultipleValueField(SelectMultipleField):\n \"\"\"Multiple value selection widget.\n\n No different from a normal multi select field, except this one can take (and\n validate) multiple choices and value (by defualt) can be a bitmap of\n selected choices (the choice value should be an integer).\n \"\"\"\n\n is_bitmap_value = True\n\n def iter_choices(self):\n \"\"\"Iterate through the list of choces.\"\"\"\n if self.is_bitmap_value and type(self.data) is int:\n for value, label in self.choices:\n yield (value, label, bool(self.data & value))\n else:\n yield from super().iter_choices()\n\n def process_data(self, value):\n \"\"\"Map selected value representation to the a list to internal domain value.\"\"\"\n try:\n if self.is_bitmap_value:\n self.data = [self.coerce(v) for (v, _) in self.choices if v & value]\n else:\n self.data = [self.coerce(v) for v in value]\n except (ValueError, TypeError):\n self.data = None\n\n def process_formdata(self, valuelist):\n \"\"\"Map submitted value to the domain value.\"\"\"\n try:\n if self.is_bitmap_value:\n self.data = sum(int(self.coerce(x)) for x in valuelist)\n else:\n self.data = [self.coerce(x) for x in valuelist]\n except ValueError:\n raise ValueError(\n self.gettext('Invalid choice(s): one or more data inputs could not be coerced'))\n\n def pre_validate(self, form):\n \"\"\"Pre-validate if it's not bit-map.\"\"\"\n if self.data and not self.is_bitmap_value:\n values = list(c[0] for c in self.choices)\n for d in self.data:\n if d not in values:\n raise ValueError(\n self.gettext(\"'%(value)s' is not a valid choice for this field\") %\n dict(value=d))\n\n\nclass RecordForm(FlaskForm):\n \"\"\"User/researcher employment detail form.\"\"\"\n\n org_name = StringField(\"Institution/employer\", [validators.required()])\n city = StringField(\"City\", [validators.required()])\n state = StringField(\"State/region\", filters=[lambda x: x or None])\n country = CountrySelectField(\"Country\", [validators.required()])\n department = StringField(\"Department\", filters=[lambda x: x or None])\n role = StringField(\"Role/title\", filters=[lambda x: x or None])\n start_date = PartialDateField(\"Start date\")\n end_date = PartialDateField(\"End date (leave blank if current)\")\n disambiguated_id = StringField(\"Disambiguated Organisation ID\")\n disambiguation_source = StringField(\"Disambiguation Source\")\n\n def __init__(self, *args, form_type=None, **kwargs):\n \"\"\"Create form.\"\"\"\n super().__init__(*args, **kwargs)\n if form_type == \"EDU\":\n self.org_name.name = self.org_name.label.text = \"Institution\"\n self.role.name = self.role.label.text = \"Course/Degree\"\n\n\nclass FileUploadForm(FlaskForm):\n \"\"\"Organisation info pre-loading form.\"\"\"\n\n file_ = FileField(\n validators=[FileRequired(),\n FileAllowed([\"csv\", \"tsv\"], 'CSV or TSV files only!')])\n\n\nclass JsonOrYamlFileUploadForm(FlaskForm):\n \"\"\"Funding info pre-loading form.\"\"\"\n\n file_ = FileField(\n validators=[FileRequired(),\n FileAllowed([\"json\", \"yaml\"], 'JSON or YAML file only!')])\n\n\nclass LogoForm(FlaskForm):\n \"\"\"Organisation Logo image upload form.\"\"\"\n\n logo_file = FileField(validators=[\n FileRequired(),\n FileAllowed([\"gif\", \"png\", \"jpg\"], 'Only image files allowed!')\n ])\n upload = SubmitField(\"Upload\", render_kw={\"class\": \"btn btn-primary\"})\n reset = SubmitField(\"Reset\", render_kw={\"class\": \"btn btn-danger\"})\n cancel = SubmitField(\"Cancel\", render_kw={\"class\": \"btn btn-invisible\"})\n\n\nclass EmailTemplateForm(FlaskForm):\n \"\"\"Email template form.\"\"\"\n\n email_template = TextField(\n widget=TextArea(), render_kw={\n \"style\": \"min-width: 800px;min-height: 550px;\"\n })\n email_template_enabled = BooleanField(default=False)\n prefill = SubmitField(\"Pre-fill\", render_kw={\"class\": \"btn btn-default\"})\n reset = SubmitField(\"Reset\", render_kw={\"class\": \"btn btn-danger\"})\n send = SubmitField(\"Send\", render_kw={\"class\": \"btn btn-primary\"})\n save = SubmitField(\"Save\", render_kw={\"class\": \"btn btn-success\"})\n cancel = SubmitField(\"Cancel\", render_kw={\"class\": \"btn btn-invisible\"})\n\n\nclass OnboardingTokenForm(FlaskForm):\n \"\"\"Form for requesting missing onboarding token.\"\"\"\n\n token = StringField(\"Token\", [validators.required()])\n\n\nclass RequiredIf(Required):\n \"\"\"Condition validator.\n\n A validator which makes a field required if\n another field is set and has a truthy value.\n \"\"\"\n\n def __init__(self, other_field_name, *args, **kwargs):\n \"\"\"Link the condtion field to the validator.\"\"\"\n self.other_field_name = other_field_name\n super().__init__(*args, **kwargs)\n\n def __call__(self, form, field):\n \"\"\"Validate conditionally if the linked field has a value.\"\"\"\n other_field = form._fields.get(self.other_field_name)\n if other_field is None:\n raise Exception(f'no field named \"{self.other_field_name}\" in form')\n if bool(other_field.data):\n super().__call__(form, field)\n\n\nclass OrgRegistrationForm(FlaskForm):\n \"\"\"Organisation registration/invitation form.\"\"\"\n\n org_name = StringField('Organisation Name', validators=[DataRequired()])\n org_email = EmailField('Organisation Email', validators=[DataRequired(), Email()])\n tech_contact = BooleanField(\"Technical Contact\", default=False)\n via_orcid = BooleanField(\"ORCID Authentication\", default=False)\n first_name = StringField(\n \"First Name\", validators=[\n RequiredIf(\"via_orcid\"),\n ])\n last_name = StringField(\n \"Last Name\", validators=[\n RequiredIf(\"via_orcid\"),\n ])\n orcid_id = StringField(\"ORCID iD\", [\n validate_orcid_id_field,\n ])\n city = StringField(\n \"City\", validators=[\n RequiredIf(\"via_orcid\"),\n ])\n state = StringField(\"State/Region\")\n country = CountrySelectField(\n \"Country\", default=DEFAULT_COUNTRY, validators=[\n RequiredIf(\"via_orcid\"),\n ])\n course_or_role = StringField(\"Course or Job title\")\n disambiguated_id = StringField(\"Disambiguated Id\")\n disambiguation_source = StringField(\"Disambiguation Source\")\n\n\nclass OrgConfirmationForm(FlaskForm):\n \"\"\"Registered organisation confirmation form.\"\"\"\n\n name = StringField('Organisation Name', validators=[DataRequired()])\n email = EmailField('Organisation EmailId', validators=[DataRequired(), Email()])\n show_api_credentials = BooleanField(\"Show API Credentials\", default=False)\n orcid_client_id = StringField(\n 'Organisation Orcid Client Id: ',\n validators=[\n DataRequired(),\n Regexp(r\"^\\S+$\", message=\"The value shouldn't contain any spaces\"),\n Regexp(\n r\"^APP-[A-Z0-9]+$\",\n message=(\"The Cient ID should match patter \"\n \"'APP-(sequence of digits or uppercase characters), \"\n \"for example, 'APP-FDFN3F52J3M4L34S'.\")),\n ])\n orcid_secret = StringField(\n 'Organisation Orcid Client Secret: ',\n validators=[\n DataRequired(),\n Regexp(r\"^\\S+$\", message=\"The value shouldn't contain any spaces\"),\n UUID(message=\"The secret should be a valid UUID\")\n ])\n country = CountrySelectField(\"Country\", [validators.required()], default=DEFAULT_COUNTRY)\n city = StringField(\"City\", [validators.required()])\n disambiguated_id = StringField(\"Disambiguated Id\", [validators.required()])\n disambiguation_source = StringField(\"Disambiguation Source\", [validators.required()])\n\n\nclass UserInvitationForm(FlaskForm):\n \"\"\"Single user invitation form.\"\"\"\n\n first_name = StringField(\"First Name\", [validators.required()])\n last_name = StringField(\"Last Name\", [validators.required()])\n email_address = EmailField(\"Email Address\", [validators.required(), Email()])\n orcid_id = StringField(\"ORCID iD\", [\n validate_orcid_id_field,\n ])\n department = StringField(\"Campus/Department\")\n organisation = StringField(\"Organisation Name\")\n city = StringField(\"City\", [validators.required()])\n state = StringField(\"State/Region\")\n country = CountrySelectField(\"Country\", [validators.required()], default=DEFAULT_COUNTRY)\n course_or_role = StringField(\"Course or Job title\")\n start_date = PartialDateField(\"Start date\")\n end_date = PartialDateField(\"End date (leave blank if current)\")\n is_student = BooleanField(\"Student\")\n is_employee = BooleanField(\"Staff\")\n disambiguated_id = StringField(\"Disambiguated Id\")\n disambiguation_source = StringField(\"Disambiguation Source\")\n resend = BooleanField(\"Resend\")\n\n\nclass DateRangeForm(FlaskForm):\n \"\"\"Simple date range selection form with ISO dates.\"\"\"\n\n from_date = DateField('DatePicker', format='%Y-%m-%d')\n to_date = DateField('DatePicker', format='%Y-%m-%d')\n\n\nclass ApplicationFromBase(FlaskForm):\n \"\"\"User/client application registration management form.\"\"\"\n\n name = StringField(\"Application name\", [validators.required()])\n homepage_url = StringField(\"Homepage URL\")\n description = TextField(\"Application Description\")\n callback_urls = TextField(\"Authorization callback URLs\")\n\n\nclass ApplicationFrom(ApplicationFromBase):\n \"\"\"Application client registration form.\"\"\"\n\n register = SubmitField(\"Register\", render_kw={\"class\": \"btn btn-primary mr-2\"})\n cancel = SubmitField(\"Cancel\", render_kw={\"class\": \"btn btn-invisible\"})\n\n\nclass CredentialForm(ApplicationFromBase):\n \"\"\"User/client application credential registration management form.\"\"\"\n\n client_id = StringField(\"Client ID\", render_kw={\"readonly\": True})\n client_secret = StringField(\"Client Secret\", render_kw={\"readonly\": True})\n revoke = SubmitField(\"Revoke all user tokens\", render_kw={\"class\": \"btn btn-danger\"})\n reset = SubmitField(\"Reset client secret\", render_kw={\"class\": \"btn btn-danger\"})\n update_app = SubmitField(\"Update application\", render_kw={\"class\": \"btn btn-primary mr-2\"})\n delete = SubmitField(\"Delete application\", render_kw={\"class\": \"btn btn-danger\"})\n\n\nclass WebhookForm(FlaskForm):\n \"\"\"Webhoook form.\"\"\"\n\n webhook_url = URLField(validators=[url()])\n webhook_enabled = BooleanField()\n email_notifications_enabled = BooleanField()\n save_webhook = SubmitField(\n \"Save\",\n render_kw={\n \"class\": \"btn btn-success\",\n \"data-toggle\": \"tooltip\",\n \"title\": \"Save Organisation webhook\"\n })\n","sub_path":"orcid_hub/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":15157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"510204457","text":"import matplotlib.pyplot as plt\nimport os\n\ndef plot_np(nparray, title=None):\n plt.scatter(nparray[:,0], nparray[:,1])\n if title:\n fig.suptitle(title, fontsize=20)\n plt.plot(nparray[0,:], 'rD')\n plt.plot(nparray[-1,:], 'ks')\n plt.show()\n\ndef plot_list(x,y, titlename=None):\n plt.scatter(x, y)\n if titlename:\n plt.title(titlename, fontsize=20)\n plt.plot(x[0], y[0], 'rD')\n plt.plot(x[-1], y[-1], 'ks')\n plt.show()\n\n\ndef plot_file(filename, title=None):\n x = []\n y = []\n with open(filename, \"r\") as trainfile:\n trainfile.readline() # skip header\n for line in trainfile:\n items = line.split(\",\")\n x.append(items[0])\n y.append(items[1])\n fig = plt.figure()\n plt.scatter(x, y)\n if title:\n fig.suptitle(title, fontsize=20)\n plt.plot(x[0], y[0], 'rD')\n plt.plot(x[-1], y[-1], 'ks')\n plt.show()\n\nif __name__ == '__main__':\n from random import sample, seed\n seed(42)\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"100.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"102.csv\"))\n #\n #\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"1.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"10.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"104.csv\"))\n #\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"101.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"108.csv\"))\n\n # Funky plots --Faked\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"107.csv\"))\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"112.csv\"))\n #\n # # Missing GPS values\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"117.csv\"))\n #\n # plot_file(os.path.join(\"data\", \"drivers_small\", \"3600\", \"92.csv\"))\n foldername = os.path.join(\"data\", \"drivers\", \"191\")\n files = [os.path.join(foldername, f) for f in os.listdir(foldername) if os.path.isfile(os.path.join(foldername, f))]\n referencenum = 10\n referencefiles = [files[i] for i in sorted(sample(xrange(len(files)), referencenum))]\n for file in referencefiles:\n plot_file(file)","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"129600136","text":"# get pasted objects for copy-and-paste augmentation method\n# objects type are among categoryNames defined below\n\nfrom pycocotools.coco import COCO\nimport cv2\nimport math\n\nann_file_path = r\"path/to/annotation.json\"\nimg_path = r'path/to/images'\ncoco = COCO(ann_file_path)\nsave_path = r'path/to/cap_all_objects/'\n\n# get category infos\ncategoryNames = ['car', 'person', 'bus', 'motorbike', 'bicycle']\ncategoryIds = coco.getCatIds(catNms=categoryNames)\ncategoryInfos = coco.loadCats(categoryIds)\ncategoryIdToName = {cat['id']: cat['name'] for cat in categoryInfos}\n# {1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle', 6: 'bus'}\ncategoryCount = {cat['id']: 1 for cat in categoryInfos}\n\n# get all anninfos\nannids = coco.getAnnIds(catIds=categoryIds)\nanninfos = coco.loadAnns(annids)\n\n# for every anninfo\nfor anninfo in anninfos:\n # get imginfo according to anninfo\n imgid = anninfo['image_id']\n imginfo = coco.loadImgs([imgid])[0]\n # download image if not exists\n imgname = imginfo['file_name']\n img = cv2.imread(img_path+imgname, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)\n # get mask according to segmentation annotation\n mask = coco.annToMask(anninfo) # 2d array, size same as img\n assert img.shape[:2] == mask.shape\n img[:, :, 3] = mask*255\n x, y, w, h = anninfo['bbox']\n if w*h <= 32*32:\n sizetype = 'small'\n elif w*h <= 96*96:\n sizetype = 'medium'\n else:\n sizetype = 'large'\n x2, y2 = x+w, y+h\n x, y = list(map(math.floor, [x, y]))\n x2, y2 = list(map(math.ceil, [x2, y2]))\n catid = anninfo['category_id']\n # save new image\n save_name = save_path+categoryIdToName[catid]+'_'+sizetype+'_'+str(categoryCount[catid])+'.png'\n cv2.imwrite(save_name, img[y:y2, x:x2])\n categoryCount[catid] += 1\n if categoryCount[catid] % 1000 == 0:\n print(f'processed {categoryIdToName[catid]} num: {categoryCount[catid]}')\n","sub_path":"utils/getPastedObjects.py","file_name":"getPastedObjects.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"288274818","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n#\r\n# Complete the 'miniMaxSum' function below.\r\n#\r\n# The function accepts INTEGER_ARRAY arr as parameter.\r\n#\r\n\r\ndef miniMaxSum(arr):\r\n # Write your code here\r\n ans = []\r\n \r\n for i in range (0,len(arr)):\r\n Sum=0\r\n for j in range (0,len(arr)):\r\n if (j == i):\r\n continue\r\n else:\r\n Sum = Sum + arr[j]\r\n ans.append(Sum)\r\n \r\n print(min(ans),max(ans))\r\n \r\n\r\nif __name__ == '__main__':\r\n\r\n arr = list(map(int, input().rstrip().split()))\r\n\r\n miniMaxSum(arr)\r\n","sub_path":"Mini-Max Sum.py","file_name":"Mini-Max Sum.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"80089967","text":"from rest_framework import viewsets\nfrom rest_framework import permissions\nfrom rest_framework.decorators import detail_route, list_route\nfrom rest_framework.response import Response\nfrom rest_framework import status as HTTPStatus\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\n\nfrom users.models import UserProfile, UserTogether\nfrom users.serializers import UserProfileSerializer, UserSerializer\n\nfrom utils.wechat import WeChat\nfrom utils.users import get_user_token_response, get_token_response_by_open_id\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n# Create your views here.\n\"\"\"\n1. 首页 LOGO\n2. 点击 LOGO 获取用户信息登录\n3. 一个人,单头像;两个人,双头像\n4. 点击下方跳转主页面\n\"\"\"\n\n\nclass UserProfileViewSet(viewsets.ModelViewSet):\n \"\"\"\n 自带有 detail 和 list\n \"\"\"\n queryset = UserProfile.objects.all()\n serializer_class = UserProfileSerializer\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n\n @list_route(methods=[\"POST\"], permission_classes=[permissions.AllowAny])\n def login(self, request):\n js_code = request.data.get(\"code\")\n open_id = request.data.get(\"open_id\")\n if open_id:\n token_response = get_token_response_by_open_id(open_id)\n return Response(token_response, status=HTTPStatus.HTTP_200_OK)\n elif js_code:\n we_chat = WeChat(settings.WECAHT_APPID, settings.WECHAT_SECRET)\n code_response = we_chat.login_by_code(js_code)\n open_id = code_response.get(\"openid\")\n if open_id:\n token_response = get_token_response_by_open_id(open_id)\n return Response(token_response, status=HTTPStatus.HTTP_200_OK)\n logger.error(\"no open_id or code\")\n return Response(\"No token\", status=HTTPStatus.HTTP_400_BAD_REQUEST)\n\n @list_route(methods=[\"GET\", \"PUT\"], permission_classes=[permissions.IsAuthenticated])\n def user_info(self, request, *args, **kwargs):\n if request.method == \"PUT\":\n profile = request.user.profile\n user_data = request.data\n avatar = user_data.pop(\"avatar\")\n partial = kwargs.pop('partial', True)\n if avatar:\n profile.avatar = avatar\n profile.save(update_fields=['avatar'])\n serializer = self.get_serializer(profile, data=user_data, partial=partial)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n\n if getattr(profile, '_prefetched_objects_cache', None):\n # If 'prefetch_related' has been applied to a queryset, we need to\n # forcibly invalidate the prefetch cache on the instance.\n profile._prefetched_objects_cache = {}\n return Response(get_user_token_response(request.user), status=HTTPStatus.HTTP_200_OK)\n\n return Response(get_user_token_response(request.user), status=HTTPStatus.HTTP_200_OK)\n\n @list_route(methods=[\"POST\"], permission_classes=[permissions.IsAuthenticated])\n def together(self, request, pk=None):\n \"\"\"创建用户关系\"\"\"\n object_id = request.data.get(\"objectID\")\n object_user = User.objects.filter(pk=object_id).first()\n if not object_user:\n logger.error(\"no such user:{}\".format(object_id))\n return Response({\"err_code\": \"40104\", \"err_msg\": \"找不到该对象\"}, status=HTTPStatus.HTTP_404_NOT_FOUND)\n\n # request.user / object_user 是否已经存在关系\n if UserTogether.objects.filter(Q(user_f=request.user) | Q(user_m=request.user)):\n logger.error(\"you already have relation with someone\")\n return Response({\"err_code\": \"40101\", \"err_msg\": \"你已经和某人建立关系了\"}, status=HTTPStatus.HTTP_409_CONFLICT)\n if UserTogether.objects.filter(Q(user_f=object_user) | Q(user_m=object_user)):\n logger.error(\"object already have relation with someone\")\n return Response({\"err_code\": \"40101\", \"err_msg\": \"对方已经和某人建立关系了\"}, status=HTTPStatus.HTTP_409_CONFLICT)\n\n # 自定义 manager 增加新的 get_or_create_together(user_a, user_b)\n user_together, is_created = UserTogether.objects.get_or_create_together(request.user, object_user)\n if not is_created:\n logger.warning(\"already exist relation with somebody\")\n return Response({\"err_code\": \"40102\", \"err_msg\": \"已经和对方建立过关系\"}, status=HTTPStatus.HTTP_409_CONFLICT)\n return Response({\"err_code\": \"0\", \"res\": {\"msg\": \"与对方成功建立关系\", \"you\": UserSerializer(object_user).data}})\n","sub_path":"Y_D/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"211707476","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''archive.py - uploads all files with approved file names from\n'../data/local/downloads/' to Google Cloud Storage.\n\nNOTE: if the files already exist in the archive, this script will overwrite\nthem. It is your responsibility to make sure you don't wipe out the archive.\n\n'''\n\n# Libraries\nimport os\nimport argparse\nimport json\nfrom pprint import pprint\nimport re\nfrom google.cloud import storage\n\n\ndef valid_filename(filename):\n '''valid_filename: determines if the given filename is a real file. Assumes that the file is in the current working directory for the program.\n\n returns: given file name\n '''\n if not os.path.isfile(filename):\n msg = \"The given file '{}' does not exist at '{}'.\".format(\n filename,\n os.getcwd()\n )\n raise argparse.ArgumentTypeError(msg)\n\n return filename\n\n\ndef parse_args():\n '''parse_args: parses command line arguments. Returns a dictionary of arguments.\n '''\n parser = argparse.ArgumentParser(\n description='Archives data files to the Requex Google Cloud Storage archive.',\n prog='archive'\n )\n\n parser.add_argument('config_file',\n type=valid_filename,\n metavar='CONFIG_FILE',\n help=\"File path to requex configuration file. File must be in JSON format.\")\n parser.add_argument('-t', '--type', choices=['raw', 'merged', 'models'],\n help=\"Specify the type of data to be archived. 'raw' archives data downloaded from external data sources in '../data/local/downloads/' and is unmodified. 'merged' archives merged data files from '../data/local/staging/'. And 'models' archvies model files from '../data/local/models/'.\")\n\n return vars(parser.parse_args())\n\n\ndef get_config_filename(filename=None):\n '''get_config_filename: returns a verified Requex configuration file name. This function handles the ambiguity around whether the module was called from a shell with command line arguments or if called from another program using the run() function. If filename is none, the function assumes that there are\n\n return: string; valid filename.\n '''\n if filename is None:\n # get command line arguments\n args = parse_args()\n filename = args['config_file']\n else:\n if not os.path.isfile(filename):\n print(\"The given file '{}' does not exist at '{}'.\".format(\n filename,\n os.getcwd()\n ))\n exit(1)\n return filename\n\n\ndef get_config(filename):\n '''get_config: reads the configuration JSON file and stores values in a dictionary for processing.\n\n PRE: assumes the file already exists\n\n return: dict of configuration settings\n '''\n\n with open(filename, \"r\") as f:\n config = json.load(f)\n\n return config\n\n\ndef upload_blob(bucket_name, source_file_name, destination_blob_name):\n \"\"\"Uploads a file to the bucket.\"\"\"\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(bucket_name)\n blob = bucket.blob(destination_blob_name)\n\n blob.upload_from_filename(source_file_name)\n\n print('success: file {} uploaded to {}.'.format(\n source_file_name,\n destination_blob_name))\n\n\ndef create_dest_filename(filename, date, file_map, data_type):\n '''create_dest_filename: takes the file name, archive date, and a dictionary that contains a file map and assembles the correct\n file path in the archive for the file's storage location.\n\n filename: the filename with extension, but without path\n date: string of the date where the file is to be stored in\n YYYY-MM-DD format\n file_map: dictionary of first three letters of a filename and the map to the root directory in the archive into which to store the file.\n data_type: Choices include: 'raw', 'merged', 'models'.\n\n returns: string; a gcs-formatted filename.\n '''\n year, month, day = date.split('-')\n\n basename = os.path.basename(filename)\n\n if data_type == 'raw':\n file_prefix = basename[:3]\n archive_dir = file_map.get(file_prefix)\n\n if archive_dir is not None:\n return archive_dir+'/'+year+'/'+month+'/'+day+'/'+basename\n else:\n return ''\n elif data_type == 'merged':\n file_prefix = basename[:len('merged')]\n if file_prefix == 'merged':\n return file_prefix+'/'+year+'/'+month+'/'+day+'/'+basename\n else:\n return ''\n elif data_type == 'models':\n # insert decision logic for 'model type' and 'model algo'\n # insert way to select the version number\n model_type = re.search(r'(?:binary|multiclass)|$', basename, flags=re.IGNORECASE).group()\n model_algo = re.search(r'(?:LSTM)|$', basename, flags=re.IGNORECASE).group()\n reg = re.compile(r'(?:_v\\d+)|$', flags=re.IGNORECASE)\n version = re.search(reg, basename).group()[1:].lower()\n if (model_type != '') and (model_algo != '') and (version != ''):\n return 'models/'+model_type+'/'+model_algo+'/'+year+'/'+month+'/'+day+'/'+version+'/'+basename\n else:\n return ''\n else:\n print(\"error: data_type '{}' is not a recognized type.\".format(data_type))\n exit(1)\n\n\ndef get_file_list(directory):\n return [f for f in os.listdir(directory)\n if os.path.isfile(directory+f)]\n\n\ndef run(config_file=None, data_type=None):\n # get configuration parameters\n config_file = get_config_filename(config_file)\n config = get_config(config_file)\n # print('configuration settings:')\n # pprint(config)\n if data_type is None:\n args = parse_args()\n data_type = args['type']\n elif data_type != 'raw' and data_type != 'merged' and data_type != 'models':\n print(\"error: archive.py called with invalid data_type option '{}'\".format(data_type))\n exit(1)\n\n # environment variable\n env_var = 'GOOGLE_APPLICATION_CREDENTIALS'\n\n # requex-svc file path for connecting to GCP storage bucket\n svc_path = config['root_dir']+config['google_auth_json']\n\n # set the local environment variable\n os.environ[env_var] = svc_path\n\n # filenames to exclude from renaming\n exclude = config['excluded_files']\n\n # approved file extensions\n if data_type == 'raw':\n # set the approved file extensions and source directory for 'raw' data\n # types.\n approved = config['data_formats_raw']\n source_dir = config['root_dir']+config['downloads_dir']\n elif data_type == 'merged':\n # set the approved file extensions and source directory for 'merged'\n # data types.\n approved = config['data_formats_merged']\n source_dir = config['root_dir']+config['staging_dir']\n elif data_type == 'models':\n # set the approved file extensions and source directory for 'models'\n # data types.\n approved = config['data_formats_models']\n source_dir = config['root_dir']+config['models_dir']\n else:\n print(\"error: data_type '{}' is not a recognized type.\".format(data_type))\n exit(1)\n\n # Google Cloud Storage archive name\n gcs_name = config['google_cloud_storage_archive']\n\n # get a list of all files in the source directory\n files = get_file_list(source_dir)\n\n # archive all file names that have a datestamp and approved extension\n for file in files:\n filename, extension = os.path.splitext(file)\n\n if filename in exclude:\n continue\n\n # only upload files with approved extensions and datestamps\n if extension in approved:\n # this makes sure a folder of files with different date stamps\n # get placed in the correct folder in the archive.\n found_date = re.search(r'\\d\\d\\d\\d-\\d\\d-\\d\\d|$', filename).group()\n if found_date != '':\n # file contains a date, archive it\n dest_file = create_dest_filename(\n source_dir+file,\n found_date,\n config['file_map'],\n data_type\n )\n if dest_file != '':\n # print(dest_file)\n upload_blob(gcs_name, source_dir+file, dest_file)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"code/pipeline/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":8340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"73430590","text":"\"\"\"prognosis_research URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('allauth.urls')),\n path('', include('home.urls')),\n path('whats_new/', include('whats_new.urls')),\n path('prognosis/', include('prognosis.urls')),\n path('our_book/', include('our_book.urls')),\n path('methods_guidance/', include('methods_guidance.urls')),\n path('videos/', include('videos.urls')),\n path('courses_and_events/', include('courses_and_events.urls')),\n path('contact/', include('contact.urls')),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"prognosis_research/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"526278758","text":"import os\nimport sys\nimport time\n# image operation\nfrom PIL import Image\nimport numpy as np\n# utils\nfrom .PCA import pca\n# detection and alignment\nfrom detection import detection\n\n# settings\ndata_root = \"./data\"\ndetector = detection.Detector()\n\n\n'''\nThis file is used to extract PCA feature of faces.\nData source: http://vis-www.cs.umass.edu/lfw/\nfaces: 13145\ntraining time: 3887 seconds (on Ubuntu 14.04, Intel core i7 3.40GHz * 8)\n\nInput face size: 150 * 170\n90% eigenvector: 89\n'''\n\ncount = 0\nimage_mat = []\nlabels = []\nfor file in os.listdir(data_root):\n # on mac os\n if file == '.DS_Store':\n continue\n\n for imagefile in os.listdir(os.path.join(data_root, file)):\n # read image\n image = Image.open(os.path.join(data_root, file, imagefile)).convert(mode='L')\n\n # detect face and landmark (must have one)\n faces = detector.detect(image)\n\n if len(faces) == 0:\n print('.', end='')\n count += 1\n sys.stdout.flush()\n continue\n\n face = np.array(faces[0].convert(mode='L'))\n\n face_vector = np.reshape(face, -1) # reshape to a row-vector\n\n image_mat.append(face_vector)\n labels.append(file)\n\nprint('\\nFind %d mis-detected faces!' % (count))\n\n# get the traning matrix\nimage_mat = np.array(image_mat, dtype=np.float32).T\nlabels = np.array(labels)\nprint(\"Collect %d faces!\" % (len(labels)))\n\n# run pca and save PC\nprint(\"Start PCA ...\")\n\nstart_time = time.time()\n[W_norm, v, mean] = pca(image_mat)\nprint('Finish in %s seconds!'%(time.time() - start_time))\n\nprint(\"saving...\")\nnp.save('../results/pca/Wnorm', W_norm)\nnp.save('../results/pca/eigenvalue', v)\nnp.save('../results/pca/mean', mean)\nprint('done!')\n","sub_path":"feature_extraction/PCA/exp_pca.py","file_name":"exp_pca.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"491588755","text":"import copy\nimport base64\nimport hmac\nimport datetime\nimport time\nimport hashlib\nfrom hashlib import sha1\nfrom email.utils import formatdate\n\nfrom calendar import timegm\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nfrom libcloud.utils.py3 import b\nfrom libcloud.utils.py3 import httplib\n\nfrom libcloud.common.base import ConnectionUserAndKey,JsonResponse\nfrom libcloud.common.types import InvalidCredsError, LibcloudError\n\nfrom libcloud.storage.base import Container,Object\nfrom libcloud.storage.drivers.s3 import BaseS3StorageDriver,BaseS3Connection\nfrom libcloud.storage.drivers.cloudfiles import CloudFilesStorageDriver\nfrom libcloud.storage.types import ContainerDoesNotExistError\nfrom libcloud.storage.types import InvalidContainerNameError\nfrom libcloud.storage.types import ContainerIsNotEmptyError\n\ndef aws_md5(data):\n \"\"\"Make an AWS-style MD5 hash (digest in base64).\"\"\"\n hasher = hashlib.new(\"sha1\")\n if hasattr(data, \"read\"):\n data.seek(0)\n while True:\n chunk = data.read(8192)\n if not chunk:\n break\n hasher.update(chunk)\n data.seek(0)\n else:\n if six.PY3 and isinstance(data, six.text_type):\n data = bytes(data, 'utf-8')\n hasher.update(data)\n\n return hasher.hexdigest()#.decode(\"ascii\")#hex(hasher.digest()).decode(\"ascii\")\n\n\nSINA_HOST = 'sinacloud.net'\n\nclass SinaResponse(JsonResponse):\n\n def success(self):\n return self.status in [httplib.OK, httplib.CREATED, httplib.NO_CONTENT]\n\n\n\nclass SinaConnection(ConnectionUserAndKey):\n\n host = SINA_HOST\n responseCls = SinaResponse\n secure = False\n\n def __init__(self,user_id,key,secure=False,host=None,port=None,url=None,timeout=None,proxy_url=None):\n super(SinaConnection,self).__init__(user_id,key,secure=False,host=host,port=port,url=url,timeout=timeout,proxy_url=proxy_url)\n\n def add_default_headers(self,headers):\n t = datetime.datetime.utcnow()\n headers['Date'] = formatdate(timegm(t.timetuple()),usegmt=True)\n return headers\n\n def pre_connect_hook(self,params,headers):\n if 'container_name' in params.keys():\n name = params['container_name']\n path = '/%s%s' %(name,self.action)\n headers['Host'] = '.'.join((params['container_name'],headers['Host']))\n else:\n path = self.action\n sign = self._get_aws_auth_param(method=self.method,headers=headers,params=params,expires=None,secret_key=self.key,path=path)\n headers['Authorization'] = 'SINA %s:%s' %(self.user_id,sign)\n params = {}\n params['formatter'] = 'json'\n return params, headers\n\n def _get_aws_auth_param(self,method,headers,params,expires,secret_key,path='/'):\n\n # StringToSign the same as S3\n # Signature = Base64(HMAC-SHA1('secret_key'),UTF-8-Encoding-Of(StringToSign))\n # ssig = Signature[5:15]\n # Authorization: SINA secret_key:ssig\n\n special_header_keys = ['content-md5', 'content-type', 'date']\n special_header_values = {'date':''}\n sina_header_values = {}\n\n headers_copy = copy.deepcopy(headers)\n for key, value in list(headers_copy.items()):\n key_lower = key.lower()\n if key_lower in special_header_keys:\n special_header_values[key_lower] = value.strip()\n elif key_lower.startswith('x-amz-') or key_lower.startswith('x-sina-'):\n sina_header_values[key.lower()] = value.strip()\n\n if 'content-md5' not in special_header_values:\n special_header_values['content-md5'] = ''\n\n if 'content-type' not in special_header_values:\n special_header_values['content-type'] = ''\n\n if 's-sina-sha1' in headers.keys():\n special_header_values['content-md5'] = headers['s-sina-sha1']\n\n special_header_values['date'] = headers['Date']\n\n keys_sorted = list(special_header_values.keys())\n keys_sorted.sort()\n\n buf = [method]\n for key in keys_sorted:\n value= special_header_values[key]\n buf.append(value)\n string_to_sign = '\\n'.join(buf)\n\n keys_sorted = list(sina_header_values.keys())\n keys_sorted.sort()\n\n sina_header_string = []\n for key in keys_sorted:\n value = sina_header_values[key]\n sina_header_string.append('%s:%s' %(key,value))\n sina_header_string = '\\n'.join(sina_header_string)\n\n values_to_sign = []\n for value in [string_to_sign,sina_header_string,path]:\n if value:\n values_to_sign.append(value)\n\n string_to_sign = '\\n'.join(values_to_sign)\n\n b64_hmac = base64.b64encode(hmac.new(b(secret_key),b(string_to_sign),sha1).digest())[5:15]\n return b64_hmac.decode('utf-8')\n\n def _user_agent(self):\n return None\n\n\n\nclass SinaStorageDriver(BaseS3StorageDriver):\n\n name = 'Sina (standard)'\n connectionCls = SinaConnection\n http_vendor_prefix = 'x-sina'\n supports_s3_multipart_upload = False\n\n def get_container(self, container_name):\n try:\n p = {}\n p['container_name'] = container_name\n response = self.connection.request(action='/?meta',params=p)\n if response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(value=None,driver=self,container_name=container_name)\n except InvalidCredsError:\n pass\n return Container(name=container_name,extra=None,driver=self)\n\n def iterate_container_objects(self, container, ex_prefix=None):\n container_path = self._get_container_path(container)\n response = self.connection.request(container_path)\n\n if response.status != httplib.OK:\n raise LibcloudError('Unexpected status code: %s' %(response.status),driver=self)\n\n objs = json.loads(response.body)\n for obj in objs['Contents']:\n extra = {}\n yield Object(name=obj['Name'],size=int(obj['Size']),hash=obj['MD5'],extra=extra,meta_data=None,container=container,driver=self)\n\n def create_container(self, container_name):\n response = self.connection.request('/%s/' %(container_name),method='PUT')\n\n if response.status == httplib.OK:\n container = Container(name=container_name,extra=None,driver=self)\n return container\n elif response.status == httplib.CONFLICT:\n raise InvalidContainerNameError(value='Container with this name already exist, The name must be unique among all the containers in the system',container_name=container_name,driver=self)\n elif response.status == httplib.BAD_REQUEST:\n raise InvalidContainerNameError(value='Container name contains invalid characters.',container_name=container_name,driver=self)\n raise LibcloudError('Unexpected status code: %s' %(response.status),driver=self)\n\n def delete_container(self, container):\n response = self.connection.request('/%s/' %(container.name),method = 'DELETE')\n if response.status == httplib.NO_CONTENT:\n return True\n elif response.status == httplib.CONFLICT:\n raise ContainerIsNotEmptyError(value='Container must be empty before it can be deleted.',container_name=container_name,driver=self)\n elif response.status == httplib.NOT_FOUND:\n raise ContainerDoesNotExistError(value=None,driver=self,container_name=container.name)\n return False\n\n def _to_containers(self,obj,xpath):\n #obj = json.loads(obj)\n for container in obj['Buckets']:\n extra = {'CreationDate':container['CreationDate'],'ConsumedBytes':int(container['ConsumedBytes'])}\n yield Container(name=container['Name'],extra=extra,driver=self)\n\n def _get_container_path(self, container):\n return '/%s/' %(container.name)\n\n def _get_object_path(self, container, object_name):\n container_url = self._get_container_path(container)\n object_name_cleaned = self._clean_object_name(object_name)\n object_path = '%s%s' %(container_url,object_name_cleaned)\n return object_path\n\n def _headers_to_object(self, object_name, container, headers):\n hash = headers['etag'].replace('\"','')\n extra = {'content_type':headers['content-type'],\n 'etag': headers['etag']}\n meta_data = {}\n\n if 'last-modified' in headers:\n extra['last_modified'] = headers['last-modified']\n\n for key, value in headers.items():\n if not key.lower().startswith(self.http_vendor_prefix + '-meta-'):\n continue\n\n key = key.replace(self.http_vendor_prefix + '-meta-','')\n meta_data[key] = value\n\n obj = Object(name=object_name,size=headers['x-filesize'],\n hash=hash,extra=extra,\n meta_data=meta_data,\n container=container,\n driver=self)\n return obj\n\n def _put_object(self, container, object_name, upload_func,\n upload_func_kwargs, method='PUT', query_args=None,\n extra=None, file_path=None, iterator=None,\n verify_hash=True, storage_class=None):\n headers = {}\n extra = extra or {}\n\n if upload_func is self._upload_file:\n with open(file_path,'rb') as fp:\n headers['s-sina-sha1'] = aws_md5(fp)\n\n content_type = extra.get('content_type',None)\n meta_data = extra.get('meta_data',None)\n acl = extra.get('acl',None)\n\n if meta_data:\n for key, value in list(meta_data.items()):\n key = self.http_vendor_prefix + '-meta-%s' %(key)\n\n if acl:\n headers[self.http_vendor_prefix + '-acl'] = acl\n\n path = self._get_object_path(container,object_name)\n\n if query_args:\n path = '?'.join((path,query_args))\n\n result_dict = self._upload_object(\n object_name=object_name,content_type=content_type,\n upload_func=upload_func,\n upload_func_kwargs=upload_func_kwargs,\n request_path=path,request_method=method,\n headers=headers,file_path=file_path,\n iterator=iterator)\n\n response = result_dict['response']\n bytes_transferred = result_dict['bytes_transferred']\n headers = response.headers\n response = response.response\n\n if response.status == httplib.OK:\n obj = Object(name=object_name,size=bytes_transferred,\n hash=None,extra={'acl':acl},\n meta_data=meta_data,container=container,\n driver=self)\n return obj\n else:\n raise LibcloudError('Unexpected status code, status_code=%s' %(response.status),driver=self)\n\n\n\n","sub_path":"libcloud/storage/drivers/sina.py","file_name":"sina.py","file_ext":"py","file_size_in_byte":10916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"26139190","text":"import boto3\nfrom botocore.client import ClientError\nimport zipfile,os\nimport utils as funct\nimport time\n\n#parameters defined\nparameter={\n\"InitBucketName\" : \"data-shivam\",\n\"BucketConfig\" : 'ap-south-1',\n\"YamlFileName\" : \"Template.yaml\",\n\"StackName\" : \"stack1\",\n\"SourceBucketName\" : \"shivam1052061\",\n\"YamlFilePath\" : \"https://shivam1052061-source.s3.ap-south-1.amazonaws.com/Template.yaml\",\n\"UploadFolderName\" : \"numbers\",\n\"deltagK\" : \"notdivby2\",\n\"deltagV\" : \"2no\"\n}\n\ns3 = boto3.resource('s3')\ntry:\n s3.create_bucket(Bucket=parameter[\"InitBucketName\"], CreateBucketConfiguration={'LocationConstraint':parameter[\"BucketConfig\"]})\nexcept ClientError:\n print(\"Data Bucket Already Created\")\n\nfunct.upload_object(parameter[\"InitBucketName\"], parameter[\"YamlFileName\"], parameter[\"YamlFileName\"])\n\nclient = boto3.client('cloudformation')\n\nstatus = funct.stack_status(parameter[\"StackName\"])\n\nif status == 'ROLLBACK_COMPLETE' or status == 'ROLLBACK_FAILED' or status == 'UPDATE_ROLLBACK_COMPLETE' or status == \\\n 'DELETE_FAILED':\n funct.delete_object(parameter[\"SourceBucketName\"])\n client.delete_stack(StackName=parameter[\"StackName\"])\n time.sleep(5)\n while funct.stack_status(parameter[\"StackName\"]) == 'DELETE_IN_PROGRESS':\n time.sleep(5)\n print(\"stack deleted\")\n funct.create_stack(parameter[\"StackName\"], parameter[\"YamlFilePath\"], parameter[\"SourceBucketName\"])\n print(\"stack created\")\nelif status == 'CREATE_COMPLETE' or status == 'UPDATE_COMPLETE':\n funct.update_stack(parameter[\"StackName\"], parameter[\"YamlFilePath\"], parameter[\"SourceBucketName\"])\n print(\"stack updated\")\nelse:\n funct.create_stack(parameter[\"StackName\"], parameter[\"YamlFilePath\"], parameter[\"SourceBucketName\"])\n print(\"stack created\")\n\nbucket = s3.Bucket(parameter[\"SourceBucketName\"])\nbucket.objects.all().delete()\n#remove hardcoding\n#main code\n\n#code for uploading the objects using the numbers folder\n\nfunct.upload_objects(parameter[\"SourceBucketName\"],parameter[\"UploadFolderName\"])\n\n'''\ni=1\nwhile i!=6:\n s3.Object(parameter[\"SourceBucketName\"], \"%d.txt\" % (i)).upload_file(Filename='numbers\\\\'+str(i)+'.txt')\n i=i+1\n'''\n\n#print(\"1-done\")\n#i=2\n#s3.Object('shivam1052061', \"%d.txt\" % (i)).upload_file(Filename='C:\\\\Users\\\\ADMIN\\\\PycharmProjects\\\\week2\\\\numbers\\\\'+str(i)+'.txt')\n\n#setting of object tags\nj=1\nclient = boto3.client('s3')\nwhile j!=5:\n if j%2==0:\n response1 = client.put_object_tagging(\n Bucket=parameter[\"SourceBucketName\"],\n Key='%d.txt'%(j),\n Tagging={\n 'TagSet': [\n {\n 'Key': 'divby2',\n 'Value': '2yes',\n\n\n },\n {\n 'Key': 'naturalno',\n 'Value': 'yes'\n }\n ]\n }\n )\n print(\"2-done\")\n\n j=j+1\n else:\n response1 = client.put_object_tagging(\n Bucket=parameter[\"SourceBucketName\"],\n Key='%d.txt' % (j),\n Tagging={\n 'TagSet': [\n {\n 'Key': 'naturalno',\n 'Value': 'yes'\n },\n {\n 'Key': 'notdivby2',\n 'Value': '2no'\n }\n ]\n }\n )\n j=j+1\n print(\"3-done\")\n#k=1\n\n#print(\"2-done\")\n#bucket = s3.Bucket('shivam1052061')\n# for my_bucket_object in bucket.objects.all():\n # print(my_bucket_object)\n# deletion of objects based on specific tags\n\n\nclient = boto3.client('s3')\n#deltagK='notdivby2'\n#deltagV='2no'\n\n\n\n#create a delete_tag function here\n\nbucket = s3.Bucket(parameter[\"SourceBucketName\"])\n\nfor key in bucket.objects.all():\n try:\n var=key.key\n response = client.get_object_tagging(\n Bucket=parameter[\"SourceBucketName\"],\n Key=var,\n )\n for tag in response.get('TagSet'):\n if tag.get('Key')==parameter[\"deltagK\"] and tag.get('Value')==parameter[\"deltagV\"]:\n response3 = client.delete_object(\n Bucket=parameter[\"SourceBucketName\"],\n Key=var\n )\n except:\n pass\n\n\n\n'''\n\nfor key in bucket.objects.all():\n var=key.key\n response = client.get_object_tagging(\n Bucket='shivam1052061',\n Key=var,\n )\n tagK = response['TagSet'][1]['Key']\n tagV = response['TagSet'][1]['Value']\n print(tagK + \" \")\n print(tagV + \" \")\n if tagK == deltagK and tagV == deltagV:\n # print(\"4-done\" + \" \")\n response3 = client.delete_object(\n Bucket='shivam1052061',\n Key=var\n )\n\n\n'''\n\n # print(\"4-doneanddusted\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n''' \n---------unused code------------\n\nclient = boto3.client('s3control')\nresponse = client.create_job(\n AccountId='682283364620 ',\n Operation={\n\n 'S3PutObjectTagging': {\n 'TagSet': [\n {\n 'Key': 'naturalnumber',\n 'Value': 'yo'\n },\n ]\n }\n },\n Report={\n 'Bucket': 'shivam1052061',\n 'Format': 'Report_CSV_20180820',\n 'Enabled': True,\n 'Prefix': 'string',\n 'ReportScope': 'AllTasks'\n },\n ClientRequestToken='',\n Manifest={\n 'Spec': {\n 'Format': 'json'\n },\n 'Location': {\n 'ObjectArn': 'string',\n 'ObjectVersionId': 'string',\n 'ETag': 'c81e728d9d4c2f636f067f89cc14862c'\n }\n },\n Description='string',\n Priority=2,\n RoleArn='string'\n)\n'''\n'''k=1\nprint(\"3-done\")\nwhile k!=10:\n response = client.get_object_tagging(\n Bucket='shivam1052061',\n Key=\"%d.txt\" % (k),\n )\n tagK=response['TagSet'][0]['Key']\n tagV = response['TagSet'][0]['Value']\n print(tagK+ \" \")\n print(tagV+ \" \")\n if tagK == deltagK and tagV == deltagV :\n print(\"4-\")\n response3 = client.delete_object(\n Bucket='shivam1052061',\n Key='%d.txt' % (k)\n )\n k=k+1\n print(\"4-done\")\n print(k)\n'''","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":5882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"643722777","text":"'''\nName: Kelsey Ackerman\nCS230: Section 5\nData: skyscrapers.csv\nURL: Link to your web application online (see extra credit)\nDescription: This program runs a streamlit application that displays skyscraper data.\nThe user can view a map graph of the data showing the locations of the structures in the skyscraper file.\nTHe user can view graphs based on structure type either viewing it by a bar graph or a piechart showing the percentage of\nbuilding types each structure makes up of the tallest buildings.\nThe user can view graphs based on country, showing the tallest structures in the country in a bar graph or comparing two\ncountries in a scatter plot.\n'''\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport streamlit as st\nimport pydeck as pdk\nimport numpy as np\nimport random\nfrom PIL import Image\n\nFILENAME = \"skyscrapers.csv\"\nB_GRAPHS = ['bar', 'pie chart']\nCOLORS = ['', 'pink', 'blue', 'cyan', 'magenta', 'purple', 'orange']\nDROPLIST = ['Home', 'By Structure Type', 'By Country', 'Map']\n\n\n# create country dropdown list\ndef country_droplist():\n # create country dropdown list\n df_countries = pd.read_csv(FILENAME, usecols=['Country']).drop_duplicates(subset=['Country'])\n # sort dataframe alphabetically\n df_sort = df_countries.sort_values(['Country'], ascending=[True])\n countries = df_sort.values.flatten().tolist()\n country_list = []\n dict_countries = {}\n # loop trhough each country\n for c in countries:\n country = c\n # get rid of leading space\n c = c.strip()\n # if country name is two words, abbreviate with first letter of each word\n if ' ' in c:\n c_split = c.split()\n c_abbrev = c_split[0][0] + c_split[1][0]\n # if country is one work, keep as one word\n else:\n c_abbrev = c\n # add c_abbrev to list\n country_list.append(c_abbrev)\n # add country to dictionary\n dict_countries[c_abbrev] = country\n\n return dict_countries, country_list\n\n\n# find how many skyscrapers are in the country in which the user will input\ndef country_df(df, country='United States'):\n # filter df to only rows where country is equal to the country the user inputs\n df_c = df[df['Country'] == country]\n df_c = df_c[['Name', 'Feet', 'Country', 'City', 'Year']]\n # sort dataframe\n df_c = df_c.sort_values(['Feet', 'Name'], ascending=[False, True])\n return df_c\n\n\n# create dataframe for building type from user input\ndef building_type(df, type='Skyscraper'):\n # filter df to only rows where type is equal to the type the user inputs\n df_type = df[df['Type'] == type]\n # specify the columns wanted for the dataframe\n df_type = df_type[['Name', 'Feet', 'Country', 'City']]\n # sort dataframe\n df_type = df_type.sort_values(['Feet', 'Name'], ascending=[False, True])\n st.subheader(f'{type}s Around the World')\n st.write(df_type)\n # get length of dataframe\n length = len(df_type)\n # if length is 10 or more, set the default value for the slider to 10\n if length >= 10:\n set_value = 10\n # else, set the default value to he length of it\n else:\n set_value = length\n return df_type, length, set_value\n\n\n# bar chart of the tallest buildings in a specific country or of the tallest skyscrapers(type of building) in the world\ndef bar_chart_country(df, country=' United States', color='orange'):\n # filter df to only rows where country is equal to the country the user inputs\n df_c = country_df(df, country)\n st.subheader(f'Structures in {country}')\n st.write(df_c)\n # sort dataframe\n sorted_df = df_c.sort_values(['Feet', 'Name'], ascending=[True, True])\n # create bar chart\n fig, ax = plt.subplots()\n x = sorted_df['Name']\n y = sorted_df['Feet']\n num = len(x)\n plt.bar(x, y, color=color)\n plt.title(f'Tallest Structures in the {country}')\n plt.ylabel('Height in Feet')\n plt.xlabel('Name of Structure')\n # rotate labels to make it easier to read\n plt.xticks(rotation=90)\n ax.set_xticks(x)\n return plt\n\n\n# function creates bar chart of different building types and shows their names and heights\ndef bar_chart_building(df, num, type='Skyscraper', color='blue'):\n # get head of rows with number specified from dataframe\n bar_df = df.head(num)\n # sort dataframe\n sorted_df = bar_df.sort_values(['Feet', 'Name'], ascending=[True, True])\n # create bar chart\n fig, ax = plt.subplots()\n # set x and y values\n x = sorted_df['Name']\n y = sorted_df['Feet']\n num = len(x)\n # plot bar chart\n plt.bar(x, y, color=color)\n plt.title(f'Top {num} Tallest {type}s in the World')\n plt.ylabel('Height in Feet')\n plt.xlabel(f'Name of {type}')\n # rotate labels to make it easier to read\n plt.xticks(rotation=90)\n ax.set_xticks(x)\n return plt\n\n# function that creates scatterplot of the heights of the buildings built in corresponding years\ndef scatter(df, c1, c2):\n # get dataframes for each country and display them\n df1 = country_df(df, c1)\n df2 = country_df(df, c2)\n st.subheader(f'Structures in{c1}')\n st.write(df1)\n st.subheader(f'Structures in{c2}')\n st.write(df2)\n # plot data\n plt.scatter(df1['Year'], df1['Feet'], color='magenta', marker='*')\n plt.scatter(df2['Year'], df2['Feet'], color='blue', marker='o')\n # create legend\n plt.legend([c1, c2], loc=0)\n plt.title(f'Years Structures were built in{c1} and{c2}')\n plt.ylabel(\"Structure's Height in Feet\")\n plt.xlabel('Year Built')\n\n return plt\n\n\n# function that creates pie chart of structure types\ndef pie_chart(df):\n # get counts of types and write to screen\n df_pie = df.groupby('Type')['Name'].count()\n st.write(df_pie)\n\n type_list = []\n count_list = []\n types = df['Type'].drop_duplicates().values.flatten().tolist()\n # for each type, add type to list, get count of structures of that type and add count to another list\n for t in types:\n data = df[df['Type'] == t]['Name'].count().astype(float)\n type_list.append(t)\n count_list.append(data)\n # plot in pie chart\n color = ['mistyrose', 'bisque', 'pink', 'azure', 'lavender', 'honeydew', 'peachpuff']\n plt.pie(count_list, labels=type_list, autopct='%1.1f%%', colors=color)\n plt.axis('equal')\n plt.title('Tallest Structure Types')\n return plt\n\n\n# call to create map graph\ndef map_graph():\n # map graph of the tallest skyscrapers around the world using the lat and long of the buildings\n st.subheader('Map of Tallest Structures Around the World')\n # create df for map\n df_map = pd.read_csv(FILENAME, usecols=['Name', 'Lat', 'Lon'])\n # rename lat and lon columns to lower case so that st.map will work\n df_map.columns = ['Name', 'lat', 'lon']\n # map df\n # set view\n view_state = pdk.ViewState(\n latitude=df_map[\"lat\"].mean(),\n longitude=df_map[\"lon\"].mean(),\n zoom=2,\n pitch=0)\n # create layer of scatterplots for each location\n layer1 = pdk.Layer('ScatterplotLayer',\n data=df_map,\n get_position='[lon, lat]',\n get_radius=100000,\n get_color=[random.randint(0, 2555), random.randint(0, 255), random.randint(0, 255)],\n pickable=True\n )\n # tool tip\n tool_tip = {\"html\": \"{Name}({lat}, {lon})\",\n \"style\": {\"backgroundColor\": \"gray\",\n \"color\": \"white\"}\n }\n # create map\n map2 = pdk.Deck(map_style='mapbox://styles/mapbox/light-v9',\n initial_view_state=view_state,\n layers=[layer1],\n tooltip=tool_tip)\n # display map\n st.pydeck_chart(map2)\n\n\ndef main():\n st.header(\"Structures Around the World\")\n st.sidebar.header('Menu')\n choice = st.sidebar.selectbox('Select a category to display data:', DROPLIST)\n # read in file as a data frame\n df = pd.read_csv(FILENAME)\n # depending on choice, display correct things on screen\n if choice == 'Home':\n img = Image.open(\"skyscraper.jpg\")\n st.image(img)\n elif choice == 'By Structure Type':\n graph = st.sidebar.radio('Chart Type', B_GRAPHS)\n\n if graph == 'bar':\n color = st.sidebar.selectbox('Select a color:', COLORS)\n # create type drop down\n type_list = df['Type'].drop_duplicates().tolist()\n types = st.sidebar.selectbox('Select a structure type:', type_list)\n # get df of building type\n result = building_type(df, types)\n bar_df = result[0]\n length = result[1]\n set_value = result[2]\n num = st.sidebar.slider('Select the amount of top structures displayed:',\n min_value=1, max_value=length, value=set_value)\n if color != '':\n st.pyplot(bar_chart_building(df, num, types, color))\n else:\n st.pyplot(bar_chart_building(df, num, types))\n\n elif graph == 'pie chart':\n st.pyplot(pie_chart(df))\n\n elif choice == 'By Country':\n # display country dropdown list and get dictionary\n country_results = country_droplist()\n # set list from results\n country_list = country_results[1]\n # set dictionary from results\n country_dict = country_results[0]\n # add selectbox for countries\n countries = st.sidebar.selectbox('Select a Country:', country_list)\n # get full country name from dictionary\n country = country_dict[countries]\n # checkbox for comparing in a scatter plot\n compare = st.sidebar.checkbox('Compare with another country', False)\n if not compare:\n color = st.sidebar.selectbox('Select a color:', COLORS)\n # make and display bar chart\n if color != '':\n st.pyplot(bar_chart_country(df, country, color))\n else:\n st.pyplot(bar_chart_country(df, country))\n else:\n countries2 = st.sidebar.selectbox('Select a Second Country:', country_list)\n country2 = country_dict[countries2]\n st.pyplot(scatter(df, country, country2))\n\n elif choice == 'Map':\n map_graph()\n\n\nmain()\n","sub_path":"project/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":10310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"319777664","text":"import logging\nimport datetime\nfrom pythonjsonlogger.jsonlogger import JsonFormatter\n\nroot = logging.getLogger(__name__)\nroot = logging.getLogger()\nroot.setLevel(logging.INFO)\n\nsh = logging.StreamHandler()\n\n# log_format= dict([\n# ('asctime', 'asctime'),\n# ('name', 'name'),\n# ('levelname', 'levelname'),\n# ('message', 'message')])\n#\n# formatter = JsonFormatter(\n# fmt=log_format,\n# ensure_ascii=False,\n# mix_extra=True,\n# mix_extra_position='tail' # optional: head, mix\n# )\n\nlog_format = '%(asctime)%(name)%(levelname):%(message)'\nformatter = JsonFormatter(log_format)\n\nsh.setFormatter(formatter)\nsh.setLevel(logging.INFO)\nroot.addHandler(sh)\n\nfor logg in [logging.getLogger()] + [logging.getLogger(name) for name in logging.root.manager.loggerDict]:\n print(logg.name, logg.handlers)\n\n\nroot.info(\n 'test mix extra in fmt',\n extra={\n 'extra1': 'extra content 1',\n 'extra2': 'extra content 2'\n })\nroot.info(\n 'test mix extra in fmt',\n extra={\n 'extra3': 'extra content 3',\n 'extra4': 'extra content 4'\n })","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"35226031","text":"import os\nimport whoosh.index\nimport whoosh.fields\nimport whoosh.query\n\n\nclass WhooshIndexer:\n def __init__(self):\n fields = {\n \"path\":whoosh.fields.ID(unique=True, stored=True),\n \"author\":whoosh.fields.KEYWORD(stored=True),\n \"date\":whoosh.fields.DATETIME(stored=True),\n \"terms\":whoosh.fields.KEYWORD(stored = True, vector=True, scorable=True),\n \"body\" : whoosh.fields.NGRAM(stored=True)\n }\n self.schema = whoosh.fields.Schema(**fields)\n\n def make_dir(self,index_dir):\n\n os.mkdir(index_dir)\n self.index = whoosh.index.create_in(index_dir,self.schema)\n\n def load_dir(self,index_dir):\n self.index = whoosh.index.open_dir(index_dir)\n\n\n def add_email(self,path,subject,sender,rcpts,date,token_body, clean_body):\n with self.index.writer() as writer:\n writer.add_document(author = sender[0], date = date,terms = token_body)\n print(str(date) + \" : \" + subject + \" : \" + sender[0])\n\n def list_documents(self):\n with self.index.searcher() as searcher:\n reader = searcher.reader()\n for doc in reader.all_doc_ids():\n if reader.has_vector(doc, \"terms\"):\n stored = reader.stored_fields(doc)\n vec = searcher.vector_as(\"frequency\", doc, \"terms\") or []\n iterator = (term for term,cnt in vec for i in range(cnt))\n stored.update({\"terms\" : iterator})\n yield stored\n\n def most_distinctive_terms(self, number=7000):\n '''特有単語の取得'''\n with self.index.reader() as reader:\n for e in reader.most_distinctive_terms(\"terms\", number):\n yield e[0], e[1].decode('utf-8')\n\n def most_frequent_terms(self, number=7000):\n '''頻出単語の取得'''\n with self.index.reader() as reader:\n for e in reader.most_frequent_terms(\"terms\", number):\n yield e[0], e[1].decode('utf-8')\n\n","sub_path":"module/whoosh_module.py","file_name":"whoosh_module.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"36755487","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 1 14:09:40 2018\n\n@author: aoieht\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom numpy.linalg import inv\nfrom datetime import timedelta\n\n#导入事件样本\nevent_path = '../raw_data/event_sample.xlsx'\nevent_sample = pd.read_excel(event_path)\nevent_sample = event_sample.set_index(event_sample['股票代码'].map(str)+'@'+event_sample['会计年度'])\n\n#导入行业信息数据\nearning_forecast_path = '../raw_data/historical_earning_forecast.xlsx'\nearning_forecast_data = pd.read_excel(earning_forecast_path)\nindustry = pd.pivot_table(earning_forecast_data,index='证券代码',columns='报告期',values='Wind行业',aggfunc='first')\n\ntmp_columns = earning_forecast_data['Wind行业'].unique()\nindustry_re = pd.DataFrame(data=None,columns=tmp_columns,index=event_sample.index)\n\nfor e in range(len(event_sample)): #按事件作匹配\n try:\n tmp_stock = event_sample.iloc[e]['股票代码']\n tmp_fy = pd.to_datetime(event_sample.iloc[e]['会计年度'])\n tmp_industry = industry.loc[tmp_stock,tmp_fy]\n if tmp_industry in industry_re.columns:\n industry_re.iloc[e][tmp_industry] = 1\n industry_re.iloc[e] = industry_re.iloc[e].fillna(0)\n else: \n continue\n \n except:\n continue\n \nexceldata = industry_re\nexceldata.to_excel('event_industry.xlsx')","sub_path":"event_industry/event_industry_calculation.py","file_name":"event_industry_calculation.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"68213232","text":"## Run the PyMC3 inference for a given input dataset and parameters\n\nimport numpy as np\nimport pymc3 as pm\nimport pymc3.math as ma\nimport theano.tensor as tt\nimport time as ttime\nimport os,sys,json\nfrom Chempy.parameter import ModelParameters\nfrom configparser import ConfigParser\n\n###########################\n# Read in parameter file\nif len(sys.argv)!=2:\n\tprint(\"Please supply parameter file\")\n\tsys.exit()\n\nConfig = ConfigParser()\nConfig.read(sys.argv[1])\n\nneural_model = Config.get('input','neural_model')\nmock_data_file = Config.get('input','mock_data_file')\noutfile = Config.get('input','outfile')\n\nall_n = json.loads(Config['inference']['all_n'])\nmax_stars = max(all_n)\nelem_err = Config.getboolean('inference','elem_err')\nmax_iteration = Config.getint('inference','max_iteration')\n\nchains = Config.getint('sampler','chains')\ncores = Config.getint('sampler','cores')\ntune = Config.getint('sampler','tune')\nn_init = Config.getint('sampler','n_init')\nn_samples = Config.getint('sampler','n_samples')\n\n######################\n\nos.chdir('/home/oliverphilcox/ChempyMulti/')\na=ModelParameters()\n\n# Load in the neural network weights\nmodel_numpy=np.load(neural_model)\nw_array_0=np.matrix(model_numpy[\"w0\"])\nb_array_0=np.matrix(model_numpy[\"b0\"])\nw_array_1=np.matrix(model_numpy[\"w1\"])\nb_array_1=np.matrix(model_numpy[\"b1\"])\n\n# Load standardization parameters\ninput_mean=model_numpy.f.in_mean\ninput_std=model_numpy.f.in_std\noutput_mean=model_numpy.f.out_mean\noutput_std=model_numpy.f.out_std\n\n# Load mock data\nmock_data=np.load(mock_data_file)\ntrue_Times = mock_data.f.true_time\nall_els = mock_data.f.elements\nmock_data.close()\n\n# Define priors\nLambda_prior_mean = a.p0[:2]\nTheta_prior_mean = a.p0[2:]\nLambda_prior_width = [0.3,0.3]\nTheta_prior_width = [0.3,0.1,0.1]\n\n# Now standardize\nstd_Lambda_prior_mean = (Lambda_prior_mean-input_mean[:2])/input_std[:2]\nstd_Lambda_prior_width = (Lambda_prior_width)/input_std[:2]\nstd_Theta_prior_mean = (Theta_prior_mean-input_mean[2:5])/input_std[2:5]\nstd_Theta_prior_width = (Theta_prior_width)/input_std[2:5]\n\n# Define critical theta edge:\nlog_SFR_crit = 0.29402\nstd_log_SFR_crit = (log_SFR_crit-input_mean[3])/input_std[3]\n\n# Define bounds on age to stop predicting out of parameter space:\nmin_time,max_time = [1.,13.8]\nstd_min_time,std_max_time=[(time-input_mean[-1])/input_std[-1] for time in [min_time,max_time]]\n\ndef n_star_inference(n_stars,iteration,elem_err=False,n_init=20000,n_samples=1000,max_stars=100): \n ## Define which stars to use\n these_stars = np.arange(max_stars)[iteration*n_stars:(iteration+1)*n_stars]\n \n ## Load in mock dataset\n mock_data=np.load(mock_data_file) #dataset\n mu_times = mock_data.f.obs_time[these_stars] #time of birth\n sigma_times = mock_data.f.obs_time_err[these_stars] #error on age\n all_els = mock_data.f.elements\n\n full_abundances = mock_data.f.abundances[these_stars] # chemical element abundances for data\n full_errors = mock_data.f.abundance_errs[these_stars] # error on abundances\n\n # Filter out correct elements:\n els = ['C','Fe','He','Mg','N','Ne','O','Si'] # TNG elements\n n_els = len(els)\n el_indices=np.zeros(len(els),dtype=int)\n for e,el in enumerate(els):\n for j in range(len(all_els)):\n if els[e]==str(all_els[j]):\n el_indices[e]=j\n break\n if j==len(all_els)-1:\n print(\"Failed to find element %s\"%el)\n obs_abundances = full_abundances[:,el_indices]\n obs_errors = full_errors[:,el_indices]\n\n # Now standardize dataset\n norm_data=(obs_abundances-output_mean)/output_std\n norm_sd = obs_errors/output_std\n\n data_obs = norm_data.ravel()\n data_sd = np.asarray(norm_sd).ravel()\n\n std_times_mean = (mu_times-input_mean[-1])/input_std[-1]\n std_times_width = sigma_times/input_std[-1]\n \n # Define stacked local priors\n Local_prior_mean = np.vstack([np.hstack([std_Theta_prior_mean,std_times_mean[i]]) for i in range(n_stars)])\n Local_prior_sigma = np.vstack([np.hstack([std_Theta_prior_width,std_times_width[i]]) for i in range(n_stars)])\n \n # Bound variables to ensure they don't exit the training parameter space\n lowBound = tt._shared(np.asarray([-5,std_log_SFR_crit,-5,std_min_time]))\n upBound = tt._shared(np.asarray([5,5,5,std_max_time]))\n \n # Create stacked mean and variances\n loc_mean=np.hstack([np.asarray(std_Theta_prior_mean).reshape(1,-1)*np.ones([n_stars,1]),std_times_mean.reshape(-1,1)])\n loc_std=np.hstack([np.asarray(std_Theta_prior_width).reshape(1,-1)*np.ones([n_stars,1]),std_times_width.reshape(-1,1)])\n \n # Share theano variables\n w0=tt._shared(w_array_0)\n b0=tt._shared(b_array_0)\n w1=tt._shared(w_array_1)\n b1=tt._shared(b_array_1)\n ones_tensor = tt.ones([n_stars,1])\n b0_all = ma.matrix_dot(ones_tensor,b0)\n b1_all = ma.matrix_dot(ones_tensor,b1)\n \n # Define PyMC3 Model\n simple_model=pm.Model()\n \n with simple_model:\n # Define priors\n Lambda = pm.Normal('Std-Lambda',mu=std_Lambda_prior_mean,\n sd=std_Lambda_prior_width,\n shape=(1,len(std_Lambda_prior_mean)))\n\n Locals = pm.Normal('Std-Local',mu=loc_mean,sd=loc_std,shape=loc_mean.shape,\n transform=pm.distributions.transforms.Interval(lowBound,upBound),\n )\n TimeSq = tt.reshape(Locals[:,-1]**2.,(n_stars,1))\n\n TruLa = pm.Deterministic('Lambda',Lambda*input_std[:2]+input_mean[:2])\n TruTh = pm.Deterministic('Thetas',Locals[:,:3]*input_std[2:5]+input_mean[2:5])\n TruTi = pm.Deterministic('Times',Locals[:,-1]*input_std[-1]+input_mean[-1])\n\n ## NEURAL NET\n Lambda_all = ma.matrix_dot(ones_tensor,Lambda)\n InputVariables = ma.concatenate([Lambda_all,Locals,TimeSq],axis=1)\n\n layer1 = ma.matrix_dot(InputVariables,w0)+b0_all\n output = ma.matrix_dot(ma.tanh(layer1),w1)+b1_all\n\n if elem_err:\n # ERRORS\n #element_error = pm.Normal('Element-Error',mu=-2,sd=1,shape=(1,n_els))\n element_error = pm.HalfCauchy('Std-Element-Error',beta=0.01/output_std,shape=(1,n_els))\n TruErr = pm.Deterministic('Element-Error',element_error*output_std)\n stacked_error = ma.matrix_dot(ones_tensor,element_error)\n tot_error = ma.sqrt(stacked_error**2.+norm_sd**2.) # NB this is all standardized by output_std here\n else:\n tot_error = norm_sd # NB: all quantities are standardized here\n\n predictions = pm.Deterministic(\"Predicted-Abundances\",output*output_std+output_mean)\n\n # Define likelihood function (unravelling output to make a multivariate gaussian)\n likelihood=pm.Normal('likelihood', mu=output.ravel(), sd=tot_error.ravel(), \n observed=norm_data.ravel())\n \n # Now sample\n init_time = ttime.time()\n with simple_model:\n samples=pm.sample(draws=n_samples,chains=chains,cores=cores,tune=tune,\n nuts_kwargs={'target_accept':0.9},init='advi+adapt_diag',n_init=n_init)\n end_time = ttime.time()-init_time\n\n def construct_output(samples):\n Lambda=samples.get_values('Lambda')[:,0,:]\n Thetas=samples.get_values('Thetas')[:,:,:]\n Times=samples.get_values('Times')[:,:]\n \n predictions = samples.get_values('Predicted-Abundances')[:,:,:]\n \n if elem_err:\n Errs = samples.get_values('Element-Error')[:,0,:]\n return Lambda,Thetas,Times,Errs,predictions\n else:\n return Lambda,Thetas,Times,predictions\n\n print(\"Finished after %.2f seconds\"%end_time)\n \n if elem_err:\n Lambda,Thetas,Times,Errs,predictions=construct_output(samples)\n return Lambda,Thetas,Times,end_time,Errs,predictions\n else:\n Lambda,Thetas,Times,predictions=construct_output(samples)\n return Lambda,Thetas,Times,end_time,predictions\n \n\n\n## RUN THE INFERENCE ##\nchain_params=[]\nfor nn in all_n:\n mini_chain=[]\n for iteration in range(max_stars//nn):\n if iteration>=max_iteration:\n break\n print(\"Starting inference using %d stars iteration %d of %d\"%(nn,iteration+1,min(max_iteration,max_stars//nn)))\n try:\n mini_chain.append(n_star_inference(nn,iteration,elem_err=elem_err,n_init=n_init,\n n_samples=n_samples,max_stars=max_stars))\n except ValueError or FloatingPointError:\n mini_chain.append(n_star_inference(nn,iteration,elem_err=elem_err,n_init=n_init,\n n_samples=n_samples,max_stars=max_stars))\n chain_params.append(mini_chain)\n\n## Save output\nprint(\"Saving output\")\nall_n = all_n[:len(chain_params)]\nall_Lambda = [[cc[0] for cc in c] for c in chain_params]\nall_Thetas = [[cc[1][:,:,:] for cc in c] for c in chain_params]\nall_Times = [[cc[2] for cc in c] for c in chain_params]\nall_timescale = [[cc[3] for cc in c] for c in chain_params]\nif elem_err:\n all_Err = [[cc[4] for cc in c] for c in chain_params]\nelse:\n all_Err=0.\nall_predictions = [[cc[-1] for cc in c] for c in chain_params]\n\nmean_timescale = [np.mean(all_timescale[i],axis=0) for i in range(len(all_timescale))]\n\nnp.savez(outfile,n_stars=all_n,Lambdas=all_Lambda,Thetas=all_Thetas,Times=all_Times,\n runtimes=all_timescale,Errors=all_Err,mean_runtimes=mean_timescale)\nprint(\"Inference complete: output saved to %s\"%outfile)\n","sub_path":"run_pymc3.py","file_name":"run_pymc3.py","file_ext":"py","file_size_in_byte":9501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"588852246","text":"import fresh_tomatoes\r\nimport movie\r\n#creating Toy Story object\r\ntoy_story = movie.Movie(\"Toy Story\",\r\n \"A story of a boy and his toys that come to live\",\r\n \"http://vignette4.wikia.nocookie.net/disney/images\"\\\r\n \"/4/4c/\"\\\r\n \"Toy-story-movie-posters-4.jpg/\"\r\n \"revision/latest?cb=20140816182710\",\r\n \"https://www.youtube.com/watch?v=4KPTXpQehio\")\r\n\r\n\r\n#creating Transformers object\r\ntransformers = movie.Movie(\"Transformers\",\r\n \"The fate of humanity is at stake when two races\"\\\r\n \"of robots,the good Autobots and the villainous\"\\\r\n \"Decepticons,bring their\"\\\r\n \"war to Earth. The robots have the\"\\\r\n \"ability to change into different mechanical\"\\\r\n \"objects\"\r\n \"as they seek the key to ultimate power. Only a\"\r\n \"human youth, Sam Witwicky (Shia LaBeouf)\"\\\r\n \"can save the world from total destruction.\",\r\n \"http://www.gstatic.com/tv/thumb/movieposters\"\r\n \"/159729/p159729_p_v8_aq.jpg\",\r\n \"https://www.youtube.com/watch?v=KrUhwet0ngg\")\r\n\r\n#creating Stomp The Yard object\r\nstomp_the_yard = movie.Movie(\"Stomp The Yard\",\r\n \"After his brother's death, a troubled but gifted\"\r\n \"street dancer enrolls in Atlanta's Truth\"\r\n \"University.As he tries to concentrate\"\r\n \"on his studies and woo a pretty\"\r\n \"classmate, he finds himself in the middle\"\\\r\n \"of a tug-of-war between fraternities, who want\"\r\n \"to utilize his talents in an upcoming\"\r\n \"dance competition.\",\r\n \"http://www.gstatic.com/tv/thumb/dvdboxart/\"\r\n \"162827/p162827_d_v8_aa.jpg\",\r\n \"https://www.youtube.com/watch?v=hvLzhK7Vatw\")\r\n#creating Get Out object\r\nget_out = movie.Movie(\"Get Out\",\r\n \"Now that Chris (Daniel Kaluuya) and his girlfriend, Rose\"\r\n \"(Allison Williams), have reached the meet-the-parents\"\\\r\n \"milestone of dating, she invites him for a weekend\"\r\n \"getaway upstate with Missy and Dean. At first, Chris\"\r\n \"reads the family's overly accommodating behavior\"\r\n \"as nervous attempts to deal with their daughter's\"\r\n \"interracial relationship,but as the weekend progresses\"\r\n \", a series of increasingly disturbing discoveries\"\r\n \"lead him to a truth that he never could have imagined.\",\r\n \"https://cdn.traileraddict.com/content/universal-pictures/\"\r\n \"get-out-2017-2.jpg\",\r\n \"https://www.youtube.com/watch?v=A2JbO9lnVLE\")\r\n\r\n#creating The Accountant object\r\nthe_accountant = movie.Movie(\"The Accountant\",\r\n \"Christian Wolff (Ben Affleck) is a mathematics\"\r\n \"savant with more affinity for numbers\"\r\n \"than people.Using a small-town CPA office\"\r\n \"as a cover, he makes his\"\r\n \"living as a freelance accountant for dangerous\"\\\r\n \"criminal organizations. With a Treasury agent\"\r\n \"(J.K. Simmons) hot on his heels,\"\r\n \"Christian takes on a\"\\\r\n \"state-of-the-art robotics company\"\r\n \"as a legitimate client\"\r\n \". As Wolff gets closer to the truth about a\"\\\r\n \"discrepancy that involves millions of dollars,\"\r\n \"the body count starts to rise.\",\r\n \"http://t0.gstatic.com/images?q=tbn:ANd9GcS\"\r\n \"TfMmvT_-0ELHJlI6OrXOoPCZqV6hlty_A6mvaABzaJRkoBgzW\",\r\n \"https://www.youtube.com/watch?v=DBfsgcswlYQ\")\r\n\r\n#creating guardians of the galaxy object\r\nguardians_of_the_galaxy = movie.Movie(\"Guardians of the Galaxy\",\r\n \"Brash space adventurer Peter Quill (Chris Pratt)\"\r\n \"finds himself the quarry of relentless bounty\"\r\n \"hunters\"\\\r\n \"after he steals an orb coveted by Ronan, a\"\r\n \"powerful villain. To evade Ronan, Quill is\"\r\n \"forced into an uneasy truce with four disparate\"\r\n \"misfits: gun-toting Rocket Raccoon,\"\r\n \"treelike-humanoid Groot,\"\\\r\n \"enigmatic Gamora, and vengeance-driven\"\r\n \"Drax the Destroyer.\"\r\n \"But when he discovers the orb's true\"\\\r\n \"power and the cosmic threat it poses, Quill must\"\r\n \"rally his ragtag group to save the universe.\",\r\n \"https://lh3.googleusercontent.com/-Glzj9zb8mRw/\"\r\n \"VDr1bPJxtTI/AAAAAAAAAMA/0VmhS2IK1Wc05tz\"\r\n \"gu4HoCN_pPROOkZcogCJoC/\"\r\n \"w800-h800/10672330_67188876625\"\r\n \"9482_6844791399166584697_n.jpg\",\r\n \"https://www.youtube.com/watch?v=d96cjJhvlMA\")\r\n#make list of favorite movies\r\nmovies = [toy_story, transformers, stomp_the_yard, get_out,\\\r\n the_accountant, guardians_of_the_galaxy]\r\n#pass list of favorite movies to open_movies_page\r\n#function defined in fresh_tomatoes\r\nfresh_tomatoes.open_movies_page(movies)\r\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"601735349","text":"import math\nimport numpy as np\nimport cv2\nfrom geo_helper import Line,Point\nclass Lane:\n\n def __init__(self):\n self.max_lines = 5\n\n\n def find_lines(self, image: np.ndarray):\n bw_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n bright_pixels = self.__find_bright_pixles(bw_image, 15)\n yellow_mask, white_mask = self.__find_white_yellow_masks(image)\n result = self.__integrate_masks(bright_pixels=bright_pixels,yellow_mask=yellow_mask, white_mask=white_mask)\n result = result * 255\n lines , mask= self.__hough_transform(result)\n return lines , mask\n\n def draw_lines_on_image(self, lines, image: np.ndarray):\n if lines is not None:\n for line in lines:\n cv2.line(img=image, pt1=(line.p1.x, line.p1.y), pt2=(line.p2.x, line.p2.y), color=(0, 0, 255),\n thickness=2)\n return image\n\n\n def __integrate_masks(self, bright_pixels: np.ndarray, yellow_mask: np.ndarray, white_mask: np.ndarray):\n white_or_yellow = cv2.bitwise_or(white_mask, yellow_mask)\n filtered_img = cv2.bitwise_and(bright_pixels,white_or_yellow)\n final_image = cv2.bitwise_or(filtered_img, yellow_mask)\n return final_image\n\n def __find_bright_pixles(self, image: np.ndarray, margin: int):\n threshold = 13 # 0.05 * 255\n bright_pixels = np.zeros_like(image)\n for y in range(0, bright_pixels.shape[0]):\n for x in range(margin, bright_pixels.shape[1] - margin):\n marg_dif = abs((int)(image[y, x-margin]) - (int)(image[y, x+margin]))\n bright_dif = 2 * (int)(image[y, x]) - (int)(image[y, x - margin]) - (int)(image[y, x + margin]) - marg_dif\n brightness = min(255, bright_dif)\n if brightness > threshold:\n bright_pixels[y,x] = 1\n return bright_pixels\n\n\n\n def __find_white_yellow_masks(self, image: np.ndarray):\n hsv_image = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\n hsv_image = np.asarray(hsv_image, dtype=np.float64) / 255\n\n hue_min = 0.1\n hue_max = 0.2\n sat_min = 0.35\n val_min = 0.5\n white_sat_max = 0.15\n white_val_min = 0.4\n\n im_mask_yellow = np.asarray(np.zeros((hsv_image.shape[0],hsv_image.shape[1])), dtype=np.uint8)\n im_mask_white = np.zeros_like(im_mask_yellow)\n for y in range(0, hsv_image.shape[0]):\n for x in range(0, hsv_image.shape[1]):\n pixel_hsv = hsv_image[y,x]\n if pixel_hsv[0] > hue_min and pixel_hsv[0] < hue_max and pixel_hsv[1] > sat_min and pixel_hsv[2] > val_min:\n im_mask_yellow[y, x] = 1\n if pixel_hsv[1] < white_sat_max and pixel_hsv[2] > white_val_min:\n im_mask_white[y, x] = 1\n return im_mask_yellow, im_mask_white\n\n def __hough_transform(self, image: np.ndarray):\n found_lines = []\n img_with_lines = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)\n lines = cv2.HoughLines(image=image, rho=20, theta=2 * np.pi / 180,threshold=10, min_theta=355 * np.pi / 180, max_theta=365 * np.pi / 180)\n if lines is not None:\n max_line_to_take = min(500, len(lines))\n for i in range(0, max_line_to_take):\n line = lines[i]\n rho = line[0][0]\n theta = line[0][1]\n a = math.cos(theta)\n b = math.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 1000 * (-b))\n y1 = int(y0 + 1000 * (a))\n x2 = int(x0 - 1000 * (-b))\n y2 = int(y0 - 1000 * (a))\n new_line = Line(Point(x1,y1), Point(x2,y2))\n self.__update_lines(found_lines,new_line, img_with_lines)\n self.draw_lines_on_image(found_lines, img_with_lines)\n return found_lines, img_with_lines\n\n\n def __update_lines(self, lines: list, new_line: Line, image: np.ndarray):\n if len(lines) >= self.max_lines:\n return\n found_close_line = False\n for existing_line in lines:\n if self.__lines_are_close(existing_line, new_line):\n found_close_line = True\n break\n\n if not found_close_line:\n lines.append(new_line)\n\n def __lines_are_close(self, line1 : Line , line2 : Line):\n if line1.intersect(line2) or line1.is_close_to(line2):\n print('found intersection: {0} , {1}'.format(line1, line2))\n return True\n return False\n\n\n\n\n\n\n\n","sub_path":"lane.py","file_name":"lane.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"378336651","text":"\"\"\"\n This test just focuses on scripts - no pyinstaller binaries\n\n After failed run:\n 1) run pg_file_ops.check\n 2) run pg_file_ops.clean\n 3) pkill sf_eventmon\n 4) remove /onefs/monitor_tests (so it can go back into DB)\n 5) close_scan_by_id --scan-id <>\n After good run:\n 1) run pg_file_ops.check\n 2) run pg_file_ops.clean\n\"\"\"\nfrom trepan.api import debug\n\nfrom configparser import RawConfigParser\nimport os\nimport shutil\nimport signal\nimport stat\nimport subprocess as sp\nimport sys\nimport time\n\nimport pathfix # this needs to be first\n\nfrom sf_em_common.close_scan_by_id import main as close_scan_by_id\nfrom sf_em_common.testutils import check_output_wrapper, custom_scan_to_json, monitor_scan_to_json, one_scan_to_json, entry_to_json\nfrom sf_em_common.utils import make_sure_datadir_exists\n\nfrom pg_file_ops_base import TestMonitorFileOpsWithPostgresBase,arg_handler\n\"\"\"\n assumes script is running in virtual env\n start running instance of monitor (through dev env python script)\n run at least one case of each type - ADDED, CHANGED, MOVED, REMOVED\n run at least one case of utf8 (exotic) and not-utf8-compatible filenames\n inspect pg DB after ADDED and then other group of file ops\n\n uses config.ini in test/\n\n REFACTOR:\n may want to rework this to use a known permanent path (/opt instead of /ifs/monitor_test)?\n\"\"\"\n\"\"\"\n Base class defines the following methods:\n start_monitor():\n wait_for_monitor():\n stop_scan():\n wait_for_queue_binding(exchange,queue):\n wait_for_events_enabled():\n setup_test_dir():\n stop_event_generation():\n close_other_scans():\n teardown_class():\n create_files(file_list):\n change_file(target_file):\n rename_file(source_file):\n remove_file(target_file):\n wait_for_db(fname, not_in=False):\n check_added_file(fs_vol,added_file):\n check_changed_file(fs_vol,changed_file,mode=None,):\n check_moved_file(fs_vol,moved_file,is_source=False):\n check_removed_file(fs_vol,removed_file):\n check_files_in_DB():\n arg_handler():\n\n\"\"\"\nclass TestMonitorFileOpsWithPostgres(TestMonitorFileOpsWithPostgresBase):\n \"\"\"\n This test needs to have sf-agent running (assume it's a local instance, for now)\n Since we're using a preloaded vsn of onefs, assume /ifs already exists and is registered to SF\n perhaps adding volume to SF can happen here, too, but assume that I'm using preconfigured onefs client for now\n \"\"\"\n def __init__(self,args):\n \"\"\"\n uses config.ini in test/ by default. specify another file with --cfg option\n \"\"\"\n super(TestMonitorFileOpsWithPostgres,self).__init__(args)\n self.args.sf_package='pg-file-ops'\n self.onefs_fs = self.fs_dir\n self.onefs_vol=self.fs_vol\n self.isihost = self.config.get('test_monitor_file_ops','isihost')\n self.share = self.config.get('test_monitor_file_ops','share')\n self.onefs_queue = self.fs_queue\n self.onefs_exchange = self.fs_exchange\n\n def start_monitor(self):\n \"\"\"\n \"\"\"\n cmd_argument_list = ['--isihost',self.isihost,'--vol',self.onefs_vol,'--filesystem',self.onefs_fs]\n self.start_monitor_from_script(cmd_argument_list)\n def stop_scan(self):\n \"\"\"\n \"\"\"\n self.stop_scan_from_script()\n\n\n def check_files_in_DB(self):\n print(\"v\"*40,'check_files_in_DB',\"v\"*40)\n\n# self.test_filesD = {'added':'fAdd','changed':'fChange','moved':'fMove','removed':'fRemove'}\n added_file = self.test_filesD['added']\n changed_file = self.test_filesD['changed']\n removed_file = self.test_filesD['removed']\n source_moved_file = self.test_filesD['moved'] \n target_moved_file = self.test_filesD['moved'] + '.moved'\n \"\"\"\n target_file_a = self.test_filesD['utf-8']\n target_file_b = self.test_filesD['non-utf8']\n \"\"\"\n\n self.check_added_file(self.onefs_vol,added_file)\n self.check_changed_file(self.onefs_vol,changed_file,mode=0o755)\n self.check_moved_file(self.onefs_vol,source_moved_file,is_source=True)\n self.check_moved_file(self.onefs_vol,target_moved_file,is_source=False)\n self.check_removed_file(self.onefs_vol,removed_file)\n\n print(\"^\"*40,'check_files_in_DB',\"^\"*40)\n\n\n#--------------------------------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n \"\"\"\n start monitor with:\n python sf_eventmon --vol ifs --filesystem /ifs --serial \\\n --scan-id ${SCAN_ID} \\\n --vol ${VOL} ${DIR}\n\n\n \"\"\"\n print(\"-\"*50 + 'Setup Monitor' + \"-\"*50)\n args = arg_handler()\n# debug()\n file_ops_test = TestMonitorFileOpsWithPostgres(args)\n file_ops_test.test_filesD = {'added':'fAdd','changed':'fChange','moved':'fMove','removed':'fRemove'}\n file_ops_test.test_filesL = [v for v in file_ops_test.test_filesD.values()]\n file_ops_test.start_monitor()\n file_ops_test.wait_for_monitor()\n file_ops_test.wait_for_events_enabled()\n print(\"-\"*50 + 'Setup Test Dir' + \"-\"*50)\n file_ops_test.setup_test_dir()\n\n print(\"-\"*50 + 'Create Files' + \"-\"*50)\n file_ops_test.create_files(file_ops_test.test_filesL)\n added_file = file_ops_test.test_filesD['added']\n changed_file = file_ops_test.test_filesD['changed']\n removed_file = file_ops_test.test_filesD['removed']\n source_moved_file = file_ops_test.test_filesD['moved'] \n target_moved_file = file_ops_test.test_filesD['moved'] + '.moved'\n file_ops_test.wait_for_db(file_ops_test.test_filesD['added'])\n file_ops_test.wait_for_db(file_ops_test.test_filesD['removed'])\n\n try:\n print(\"-\"*50 + 'New File Ops' + \"-\"*50)\n file_ops_test.change_file(changed_file)\n file_ops_test.rename_file(source_moved_file)\n file_ops_test.wait_for_db(source_moved_file,True)\n file_ops_test.wait_for_db(target_moved_file)\n file_ops_test.remove_file(removed_file)\n file_ops_test.wait_for_db(file_ops_test.test_filesD['removed'],True)\n print(\"-\"*50 + 'Check Files' + \"-\"*50)\n file_ops_test.check_files_in_DB()\n except Exception:\n file_ops_test.stop_scan()\n file_ops_test.close_other_scans()\n raise Exception('Failure during file ops')\n try:\n#first close scan\n print(\"-\"*50 + 'Stop Scan' + \"-\"*50)\n file_ops_test.stop_scan()\n file_ops_test.stop_event_generation()\n except Exception:\n print(\"-\"*50 + 'Remove other Scans' + \"-\"*50)\n file_ops_test.close_other_scans()\n\n#clean DB, kill sf_eventmon\n print(\"-\"*50 + 'Stop Monitor' + \"-\"*50)\n# file_ops_test.teardown_class()\n","sub_path":"sf-onefs/tests/pg_file_ops.py","file_name":"pg_file_ops.py","file_ext":"py","file_size_in_byte":6683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"3843858","text":"import discord\nimport asyncio\nimport random\nimport aiohttp\nimport re\nfrom discord.ext import commands\nfrom config.secrets import *\nfrom utils.checks import embed_perms, cmd_prefix_len\nimport logging\nfrom urllib import parse\nfrom urllib.request import Request, urlopen\nfrom pymongo import MongoClient\nfrom datetime import datetime as dt\nfrom pprint import pformat\n\nlogger = logging.getLogger('discord')\n\nclass Roleplay(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.session = aiohttp.ClientSession(loop=self.bot.loop, headers={\"User-Agent\": \"AppuSelfBot\"})\n self.mongo_client = MongoClient()\n self.rp_db = self.mongo_client['rp']\n self.xp = self.rp_db.xp\n self.characters = self.rp_db.characters\n\n async def log_post(self, message):\n player_id = hash(message.author)\n res = self.xp.find_one(\n {\n 'id': player_id\n }\n )\n if not res:\n res = await self.create_xp(message=message)\n \n player_hist = res['history']\n player_xp = res['xp']\n now = dt.now()\n date = str(now.year*10000 + now.month*100 + now.day)\n if date in player_hist:\n player_hist[date] += 1\n else:\n player_hist[date] = 1\n player_xp += 1\n\n self.xp.update_one(\n {\n 'id': player_id\n },\n {\n '$set': {\n 'history': player_hist,\n 'xp': player_xp\n }\n }\n )\n\n async def create_xp(self, ctx=None, message=None, member=None):\n if not message:\n message = ctx.message\n if not member:\n member = message.author\n player_id = hash(member)\n player_name = str(member)\n res = self.xp.find_one(\n {\n 'name': player_name\n }\n )\n if res:\n channel = self.bot.get_channel(BOT_DEBUG_CHANNEL)\n await channel.send('Error: {}({}) already exists in database'.format(player_name, player_id))\n return res\n ret = {\n 'id': player_id,\n 'name': player_name,\n 'xp': 0,\n 'history': {}\n }\n self.xp.insert_one(ret)\n return ret\n\n async def create_character(self, ctx, name):\n message = ctx.message\n member = message.author\n player_id = hash(member)\n player_name = str(member)\n char_name = name\n res = self.characters.find_one(\n {\n 'name': player_name\n }\n )\n if res:\n channel = self.bot.get_channel(BOT_DEBUG_CHANNEL)\n await channel.send('Error: {}({}) already exists in database'.format(player_name, player_id))\n return res\n ret = {\n 'id': player_id,\n 'name': player_name,\n 'wounds': 0,\n 'strain': 0,\n 'soak': 0,\n 'defense': {\n 'ranged': 0,\n 'melee': 0\n },\n 'character': {\n 'name': char_name,\n 'career': '',\n 'specializations': [],\n 'species': '',\n 'base_skills': {\n 'INT': 0,\n 'BRA': 0,\n 'PRE': 0,\n 'WIL': 0,\n 'AGI': 0,\n 'CUN': 0\n },\n 'ranks': {\n 'astrogation': 0,\n 'athletics': 0,\n 'brawl': 0,\n 'charm': 0,\n 'coercion': 0,\n 'computers': 0,\n 'cool': 0,\n 'coordination': 0,\n 'cybernetics': 0,\n 'deception': 0,\n 'discipline': 0,\n 'education': 0,\n 'gunnery': 0,\n 'knowledge core worlds': 0,\n 'knowledge education': 0,\n 'knowledge lore': 0,\n 'knowledge outer rim': 0,\n 'knowledge underworld': 0,\n 'knowledge warfare': 0,\n 'knowledge xenology': 0,\n 'leadership': 0,\n 'lightsaber': 0,\n 'mechanics': 0,\n 'medicine': 0,\n 'melee': 0,\n 'negotiation': 0,\n 'perception': 0,\n 'piloting planetary': 0,\n 'piloting space': 0,\n 'ranged heavy': 0,\n 'ranged light': 0,\n 'resilience': 0,\n 'skullduggery': 0,\n 'stealth': 0,\n 'streetwise': 0,\n 'survival': 0,\n 'vigilance': 0,\n },\n 'skill_characteristic': {\n 'INT': [\n 'astrogation',\n 'computers',\n 'knowledge core worlds',\n 'knowledge education',\n 'knowledge lore',\n 'knowledge outer rim',\n 'knowledge underworld',\n 'knowledge warfare',\n 'knowledge xenology',\n 'cybernetics',\n 'mechanics',\n 'medicine'\n ],\n 'BRA': [\n 'athletics',\n 'brawl',\n 'lightsaber',\n 'melee',\n 'resilience'\n ],\n 'PRE': [\n 'charm',\n 'cool',\n 'leadership',\n 'negotiation'\n ],\n 'WIL': [\n 'coercion',\n 'discipline',\n 'vigilance'\n ],\n 'AGI': [\n 'coordination',\n 'gunnery',\n 'piloting planetary',\n 'piloting space',\n 'ranged heavy',\n 'ranged light',\n 'stealth'\n ],\n 'CUN': [\n 'deception',\n 'perception',\n 'skullduggery',\n 'streetwise',\n 'survival'\n ]\n },\n 'duty': {\n 'type': '',\n 'points': ''\n },\n 'critical_injuries': [],\n 'weapons': [],\n 'equipment': [],\n 'talents': [],\n 'credits': [],\n 'max_encumberance': 0,\n 'total_xp': 0,\n 'available_xp': 0,\n 'history_brief': '',\n 'appearance_brief': '',\n 'thumbnail': ''\n }\n }\n self.characters.insert_one(ret)\n return ret\n\n async def report_characters_pid(self, ctx, player_id):\n char = self.characters.find_one(\n {\n 'id': player_id\n }\n )\n # # Thanks to IgneelDxD for help on this\n # if str(user.avatar_url)[54:].startswith('a_'):\n # avi = 'https://images.discordapp.net/avatars/' + str(user.avatar_url)[35:-10]\n # else:\n # avi = user.avatar_url \n if char:\n if embed_perms(ctx.message):\n em = discord.Embed(colour=0x708DD0)\n name = char['name'] if char['name'] else 'None'\n character = char['character']['name'] if char['character']['name'] else 'None'\n career = char['character']['career'] if char['character']['career'] else 'None'\n specializations = ', '.join(char['character']['specializations']) if char['character']['specializations'] else 'None'\n species = char['character']['species'] if char['character']['species'] else 'None'\n appearance = char['character']['appearance_brief'] if char['character']['appearance_brief'] else 'None'\n em.add_field(name='Player', value=name, inline=True)\n em.add_field(name='Character', value=character, inline=True)\n em.add_field(name='Characteristics', value=' '.join(['**{0}**:{1}'.format(s, char['character']['base_skills'][s]) for s in char['character']['base_skills']]), inline=True)\n em.add_field(name='Career', value=career, inline=True)\n em.add_field(name='Species', value=species, inline=True)\n em.add_field(name='Specializations', value=specializations, inline=True)\n em.add_field(name='Appearance', value=appearance, inline=True)\n try:\n em.set_thumbnail(url=char['character']['thumbnail'])\n except:\n pass\n await ctx.send(embed=em)\n else:\n msg = 'Unimplemented'\n await ctx.send(msg) \n else:\n await ctx.send('Character not found.')\n\n async def get_player_by_ctx(self, ctx):\n player_id = hash(ctx.message.author)\n res = self.xp.find_one(\n {\n 'id': player_id\n }\n )\n if not res:\n res = await self.create_xp(ctx=ctx)\n return res\n\n async def get_player_by_id(self, ctx, player_id):\n res = self.xp.find_one(\n {\n 'id': hash(player_id)\n }\n )\n if not res:\n res = await self.create_xp(ctx=ctx)\n return res\n\n async def get_player_by_member(self, ctx, member):\n res = self.xp.find_one(\n {\n 'id': hash(member)\n }\n )\n if not res:\n res = await self.create_xp(ctx=ctx, member=member)\n return res\n\n @commands.command(pass_context=True, aliases=['new_character'])\n async def newchar(self, ctx, name):\n await self.create_character(ctx, name)\n await ctx.send('Character created.')\n\n @commands.command(pass_context=True, aliases=['character'])\n async def char(self, ctx):\n message = ctx.message\n member = message.author\n player_id = hash(member)\n await self.report_characters_pid(ctx, player_id)\n\n @commands.command(pass_context=True, aliases=['listxpraw'])\n async def xplistraw(self, ctx):\n res = self.xp.find()\n for entry in res:\n await ctx.send(pformat(entry))\n\n @commands.command(pass_context=True, aliases=['listxp'])\n async def xplist(self, ctx):\n res = self.xp.find()\n for entry in res:\n user = ctx.guild.get_member_named(entry['name'])\n try:\n if user.nick:\n username = user.nick\n else:\n username = user.name\n except:\n username = user.name\n await ctx.send('{} has {} XP.'.format(username, entry['xp']))\n\n @commands.command(pass_context=True)\n @commands.has_role(\"Vanir\")\n async def find_one(self, ctx, query: str):\n res = self.xp.find_one(\n eval(query)\n )\n await ctx.send(pformat(res))\n\n @commands.command(pass_context=True)\n @commands.has_role(\"Vanir\")\n async def update_one(self, ctx, query: str, request: str):\n res = self.xp.update_one(\n eval(query),\n eval(request)\n )\n await ctx.send(pformat(res))\n\n @commands.has_role(\"GameMaster\")\n @commands.command(pass_context=True)\n async def givexp(self, ctx, points: int, *, name: discord.Member=None):\n if name:\n try:\n user = ctx.message.mentions[0]\n except:\n user = ctx.guild.get_member_named(name)\n if not user:\n user = ctx.guild.get_member(int(name))\n if not user:\n await ctx.send('Could not find user.')\n return\n else:\n user = ctx.message.author\n res = await self.get_player_by_member(ctx, user)\n self.xp.update_one(\n {\n 'id': res['id']\n },\n {'$set': {\n 'xp': res['xp'] + points\n }}\n )\n await ctx.send(\"{0}'s XP is increased by {1}.\".format(res['name'], points))\n\n @commands.has_role(\"GameMaster\")\n @commands.command(aliases=['set_xp'],pass_context=True)\n async def setxp(self, ctx, points: int, *, name: discord.Member=None):\n # await ctx.send(\"{},{}\".format(points, name))\n if name:\n try:\n user = ctx.message.mentions[0]\n except:\n user = ctx.guild.get_member_named(name)\n if not user:\n user = ctx.guild.get_member(int(name))\n if not user:\n await ctx.send('Could not find user.')\n return\n else:\n user = ctx.message.author\n res = await self.get_player_by_member(ctx, user)\n # await ctx.send(\"{},{},{},{}\".format(user,hash(user),res,hash(ctx.message.author)))\n self.xp.update_one(\n {\n 'id': res['id']\n },\n {'$set': {\n 'xp': points\n }}\n )\n await ctx.send(\"{0}'s XP is set to {1}.\".format(str(user), points))\n\n @commands.command(aliases=['experience'],pass_context=True)\n async def xp(self, ctx, name: discord.Member=None):\n if name:\n try:\n user = ctx.message.mentions[0]\n except:\n user = ctx.guild.get_member_named(name)\n if not user:\n user = ctx.guild.get_member(int(name))\n if not user:\n await ctx.send('Could not find user.')\n return\n else:\n user = ctx.message.author\n res = await self.get_player_by_member(ctx,user)\n msg = await ctx.send('{} has {} xp.'.format(str(user), res['xp'])) \n\n @commands.command(aliases=['test'],pass_context=True)\n async def xptest(self, ctx):\n logger.debug('Calling XPtest')\n msg = await ctx.send('You have 10000000 xp.') ","sub_path":"commands/ded/rp.py","file_name":"rp.py","file_ext":"py","file_size_in_byte":14572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"263050242","text":"import datetime\n\nfrom markupupdowndown import config\nfrom markupupdowndown.generators import render_plugin_skel\n\n\ndef init_subparser(subparsers):\n help_msg = 'create new plugin'\n parser_plugin = subparsers.add_parser('plugin', help=help_msg)\n parser_plugin.set_defaults(func=command_plugin)\n parser_plugin.add_argument('slug', action='store',\n help=\"path name for plugin\")\n\n\ndef command_plugin(args):\n render_plugin_skel(args.slug)\n","sub_path":"markupupdowndown/commands/new/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"201127865","text":"import shutil\n\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport re\nimport requests\nimport random\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nPIC_NUM = 505\n\ndef mkdir(path):\n floder = os.path.exists(path)\n if not floder:\n os.makedirs(path)\n print(\"new folder...\")\n print(\"OK\")\n else:\n print(\"there is a folder!\")\n\ndef get_dir_size(dir):\n size = 0\n for root, dirs, files in os.walk(dir):\n size += sum([os.path.getsize(os.path.join(root, name)) for name in files])\n return size\n\nheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/56.0.2924.87 Safari/537.36'}\n\nfileList = {'sunflower':'%E5%90%91%E6%97%A5%E8%91%B5','rose':\"%E7%8E%AB%E7%91%B0\",\n 'dandelion':\"%E8%92%B2%E5%85%AC%E8%8B%B1\",'daisy':'%E9%9B%8F%E8%8F%8A',\n 'tulip':\"%E9%83%81%E9%87%91%E9%A6%99\"}\n\nmkdir(\"temp\")\nfor item in fileList.keys():\n mkdir(item)\n page = 0\n count = 0\n while (count < PIC_NUM):\n print(str(count))\n url = \"https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=\"+fileList[item]+\"&pn=\"+str(count)+\\\n \"&ct=&ic=0&lm=-1&width=0&height=0\"\n print(url)\n html = urlopen(url).read().decode('utf-8')\n with open(\"temp\"+\"//\"+item+str(page)+'.html', 'w') as fp:\n fp.write(html)\n for addr in re.findall(str('\"objURL\":\"(.*?)\"'), html, re.S):\n if(count > PIC_NUM-1):\n continue\n print(\"正在爬取第\"+str(count)+\"张图片:\"+addr)\n try:\n pics = requests.get(addr,timeout = 10)\n except requests.exceptions.ConnectionError:\n print(\"Url请求错误\")\n fq = open(item+\"//\"+str(count)+\".png\", 'w+b')\n fq.write(pics.content)\n fq.close()\n count += 1\n print('下载完成。'+str(count))\n page += 1\n\nmkdir(\"test\")\nfor item in fileList.keys():\n for i in range(0,5):\n shutil.move(item+'//'+str(random.randint(0,505))+'.png', 'test//'+item+str(i)+'.png')\n\n\nsize = {}\nfor item in fileList.keys():\n size[item] = get_dir_size(item)\n print(item+' size is: %.3f Mb' % (size[item] / 1024 / 1024))\nsize['test'] = get_dir_size('test')\n\nprint('test size is: %.3f Mb' % (size['test'] / 1024 / 1024))\n#print(size)\n\n\nsunflower = [0]\nrose = [0]\ni = 0\nfor root, dirs, files in os.walk('sunflower'):\n sunflower = np.array([os.path.getsize(os.path.join(root, name)) for name in files]) / 1024\n i += 1\nsunflower.sort()\n#print(sunflower)\ni = 0\nfor root, dirs, files in os.walk('rose'):\n rose = np.array([os.path.getsize(os.path.join(root, name)) for name in files]) / 1024\n i += 1\nrose.sort()\n#print(rose)\nX = np.linspace(1,500,500,endpoint=True)\n\nsunflowerMean=np.mean(sunflower)\nroseMean = np.mean(rose)\n\nsunflowerVar = np.var(sunflower)\nprint('方差值为:'+str(sunflowerVar))\nroseVar = np.var(rose)\nprint('方差值为:'+str(roseVar))\n\n#曲线\nplt.scatter(X, sunflower, color = \"blue\", linewidth = 1.0,linestyle=\"-\", label = \"sunflower\")\nplt.scatter(X, rose, color = \"green\", linewidth = 1.0,linestyle=\"-\", label = \"rose\")\n#均值\nplt.axhline(y = sunflowerMean,color=\"red\",linestyle=\"dotted\", label = \"sunflowerMean\")\nplt.axhline(y = roseMean,color=\"grey\",linestyle=\"dotted\", label = \"sunflowerMean\")\n#99%分位线\nsunflowerPercentile99 = np.percentile(sunflower, 99)\nrosePercentile99 = np.percentile(rose, 99)\nplt.axhline(y = sunflowerPercentile99,color=\"yellow\",linestyle=\"dotted\", label = \"sunflowerPercentile99\")\nplt.axhline(y = rosePercentile99,color=\"black\",linestyle=\"dotted\", label = \"rosePercentile99\")\n#80%分位线\nsunflowerPercentile80 = np.percentile(sunflower, 80)\nrosePercentile80 = np.percentile(rose, 80)\nplt.axhline(y = sunflowerPercentile80,color='aliceblue',linestyle=\"dotted\", label = \"sunflowerPercentile80\")\nplt.axhline(y = rosePercentile80,color='mediumseagreen',linestyle=\"dotted\", label = \"rosePercentile80\")\n\nplt.xlabel(\"Pics\",fontsize=15)\nplt.ylabel(\"KB\",fontsize=15)\nplt.legend(loc='upper left')\n\nplt.show()","sub_path":"Spider.py","file_name":"Spider.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"652082295","text":"import pyautogui\nimport time\nimport sys\nimport datetime\n\n# sys.path.insert(0,'../');\n\nfrom firefox_auto import firefox_auto_api;\nfrom insta_auto import positionCache;\n\npyautogui.FAILSAFE = True;\npyautogui.PAUSE = 2;\n\n\n# insta_auto config data\nlogMessageFileObj = None;\n\ndisplayResolution = 1080; # 1920x1080x32\n\nnextImage_ICON = \"\";\nprevImage_ICON = \"\";\nlikeImage_ICON = \"\";\nlikedImage_ICON = \"\";\n\nnoOfPagesDownsForLatestPic = 0;\nfirstLatestImageLocationX = 0;\nfirstLatestImageLocationY = 0;\npixelRangeForFirstLatestImage = 0;\n\nretryLimit = 7;\nretryDelay = 1;\n\n\n# log screenshot to file\ndef logScreenshot(fileName = \"a.jpg\"):\n pyautogui.screenshot(fileName);\n\n\n# log message to log file\ndef logMessage(fileName = \"insta_auto_api.log\",msg = \"\"):\n global logMessageFileObj;\n \n T = str(datetime.datetime.now());\n \n if(logMessageFileObj == None):\n logMessageFileObj = open(fileName,\"a\");\n logMessageFileObj.write(T+\"::\"+msg+\"\\n\");\n \n\n\n# initialize insta config data\ndef init_InstaAutoConfigData(display_resolution = 1080,\n retry_limit = 7,\n retry_delay = 2):\n \n global displayResolution;\n\n global nextImage_ICON;\n global prevImage_ICON;\n global likeImage_ICON;\n global likedImage_ICON;\n\n global noOfPagesDownsForLatestPic;\n global firstLatestImageLocationX;\n global firstLatestImageLocationY;\n global pixelRangeForFirstLatestImage;\n\n global retryLimit;\n global retryDelay;\n\n\n retryLimit = retry_limit;\n retryDelay = retry_delay;\n\n \n if(displayResolution == 600):\n displayResolution = 600;\n\n nextImage_ICON = 'data/images/insta_NextImage_disp800x600_2122017.png';\n prevImage_ICON = 'data/images/insta_PrevImage_disp800x600_2122017.png';\n likeImage_ICON = 'data/images/insta_Like_disp800x600_2122017.png';\n likedImage_ICON = 'data/images/insta_Liked_disp800x600_2122017.png';\n\n noOfPagesDownsForLatestPic = 2;\n firstLatestImageLocationX = 127;\n firstLatestImageLocationY = 531;\n pixelRangeForFirstLatestImage = 20;\n\n elif(displayResolution == 720):\n displayResolution = 720;\n\n nextImage_ICON = './data/images/insta_NextImage_disp1280x720_15012018.png';\n prevImage_ICON = './data/images/insta_PrevImage_disp1280x720_15012018.png';\n likeImage_ICON = './data/images/insta_Like_disp1280x720_15012018.png';\n likedImage_ICON = './data/images/insta_Liked_disp1280x720_15012018.png';\n\n noOfPagesDownsForLatestPic = 2;\n firstLatestImageLocationX = 289;\n firstLatestImageLocationY = 646;\n pixelRangeForFirstLatestImage = 50;\n\n elif(displayResolution == 1080):\n displayResolution = 1080;\n\n nextImage_ICON = './data/images/insta_NextImage_disp1280x720_15012018.png';\n prevImage_ICON = './data/images/insta_PrevImage_disp1280x720_15012018.png';\n likeImage_ICON = './data/images/insta_Like_disp1280x720_15012018.png';\n likedImage_ICON = './data/images/insta_Liked_disp1280x720_15012018.png';\n\n noOfPagesDownsForLatestPic = 1;\n firstLatestImageLocationX = 560;\n firstLatestImageLocationY = 750;\n pixelRangeForFirstLatestImage = 100;\n\n return True;\n\n\n\n\n\n\n\ndef clickLatestPic():\n try:\n # go to home/start of page\n ret_val = firefox_auto_api.goToTopOfPage();\n if(ret_val == None or ret_val == False):\n logMessage(msg = \"Error: firefox api failed to go top of the page\");\n return False;\n\n # go two pages down\n ret_val = firefox_auto_api.goPageDown(noOfPages = noOfPagesDownsForLatestPic);\n if(ret_val == None or ret_val == False):\n logMessage(msg = \"Error: firefox api failed to go down page for No.of pages :\"+str(noOfPagesDownsForLatestPic));\n return False;\n \n # click on possible first image\n try:\n pyautogui.click(firstLatestImageLocationX, firstLatestImageLocationY);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to click on first image, err:\"+str(e));\n return False;\n \n # wait till the image loads\n count = 0;\n while(count < retryLimit):\n xy = isNextImage();\n if(xy == None): \n time.sleep(retryDelay);\n else:\n break;\n count += 1;\n \n if(count >= retryLimit):\n logMessage(msg = \"Error: Latest Image is not loaded after multiple tries\");\n return False;\n \n except Exception as e:\n logMessage(msg = \"Error: unknown cause: \"+str(e));\n return None;\n \n return True;\n\n\n\n\n\nnextIMG_positionCache = positionCache.positionCache(img = nextImage_ICON);\ndef isNextImage():\n global nextIMG_positionCache;\n try:\n # nextIMG_position = pyautogui.locateOnScreen(nextImage_ICON);\n nextIMG_position = nextIMG_positionCache.locateOnScreen(img = nextImage_ICON);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to locate next icon to confirm next Image; with err :\"+str(e));\n return None;\n return nextIMG_position;\n\n\n\n\nprevIMG_positionCache = positionCache.positionCache(img = prevImage_ICON);\ndef isPrevImage():\n global prevIMG_positionCache;\n \n try:\n # prevIMG_position = pyautogui.locateOnScreen(prevImage_ICON);\n prevIMG_position = prevIMG_positionCache.locateOnScreen(img = prevImage_ICON);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to locate prev-icon to confirm prev image; with err :\"+str(e));\n return None;\n return prevIMG_position;\n \n\n\n\n\nlike_positionCache = positionCache.positionCache(img = likeImage_ICON);\ndef likeImage():\n global like_positionCache;\n \n try:\n # get like icon position\n # like_position = pyautogui.locateOnScreen(likeImage_ICON);\n like_position = like_positionCache.locateOnScreen(img = likeImage_ICON);\n if(like_position == None):\n logMessage(msg = \"Error: pyautogui failed to locate like icon\");\n return False;\n else:\n # click like\n try:\n pyautogui.click(like_position[0]+10, like_position[1]+10);\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to click like; with err :\"+str(e));\n return False;\n # confirm liked\n if(isLiked() == None or isLiked() == False):\n logMessage(msg = \"Error: clicking like did not work. like icon did not turn liked!\");\n return False;\n except Exception as e:\n logMessage(msg = \"Error: unknown error while liking image; with err :\"+str(e));\n return None;\n\n return True;\n\n\n\n\nliked_positionCache = positionCache.positionCache(img = likedImage_ICON);\ndef isLiked():\n global liked_positionCache;\n \n try:\n # liked_position = pyautogui.locateOnScreen(likedImage_ICON);\n liked_position = liked_positionCache.locateOnScreen(img = likedImage_ICON);\n if(liked_position == None):\n return False;\n except Exception as e:\n logMessage(msg = \"Error: pyautogui failed to locate liked icon with err :\"+str(e));\n return None;\n \n return True;\n\n\n\n\n\ndef nextImage():\n global nextIMG_positionCache;\n \n try:\n # nextIMG_position = pyautogui.locateOnScreen(nextImage_ICON);\n nextIMG_position = nextIMG_positionCache.locateOnScreen(img = nextImage_ICON);\n if(nextIMG_position == None):\n logMessage(msg = \"Error: pyautogui failed to locate next icon\");\n return False;\n else:\n pyautogui.click(nextIMG_position[0]+5,nextIMG_position[1]+5);\n except Exception as e:\n logMessage(msg = \"Error: unknown error while locating next icon with err :\"+str(e));\n return None;\n \n return True;\n\n\n\n\n\n\n\ndef getHashTagLink(tag = None):\n if(tag == None):\n logMessage(msg = \"Error: no tag passed to generate instagram hash-tag link\");\n return None;\n \n link = \"https://www.instagram.com/explore/tags/\"+tag+\"/\";\n \n return link;\n\n","sub_path":"insta_auto/insta_auto_api.py","file_name":"insta_auto_api.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"527599781","text":"\"\"\"\nFunctions to modify customer information in the customers.db table.\n\"\"\"\nimport logging\nfrom peewee import JOIN, DoesNotExist\nimport create_db\nimport customer_model as cm\n\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\ncreate_db.main()\n\n\ndef add_customer(customer_id, name, lastname, home_address, phone_number, email_address, active, credit_limit):\n \"\"\"\n Adds a customer to the database. Must have all parameters set for full customer record.\n\n :param customer_id: Customer identification number\n :param name: First name\n :param lastname: Last name\n :param home_address: Home address of customer\n :param phone_number: Phone number of customer\n :param email_address: Email address of current customer\n :param active: Boolean of customer status\n :param credit_limit: Customer's credit limit\n :return: None\n \"\"\"\n try:\n with cm.database.transaction():\n contact_id = cm.Identity.create(\n customer_id=customer_id,\n name=name,\n last_name=lastname,\n credit_limit=credit_limit,\n active=active\n )\n contact_id.save()\n LOGGER.info(f\"Succesfully added record to Identity {contact_id.customer_id}: {contact_id.last_name}\")\n\n except Exception as e:\n LOGGER.info(f'Error creating = {customer_id}: {name} {lastname}')\n LOGGER.info(e)\n\n try:\n with cm.database.transaction():\n contact_info = cm.Contact.create(\n home_address=home_address,\n email_address=email_address,\n phone_number=phone_number,\n customer_id=customer_id\n )\n contact_info.save()\n\n LOGGER.info(f\"Contact updated successfully with {contact_info.customer_id}: {contact_info.home_address}\")\n\n except Exception as e:\n LOGGER.info(f'Error creating = {customer_id}: {home_address}')\n LOGGER.info(e)\n\n\ndef search_customer(customer_id):\n \"\"\"\n Finds a customer information based on their\n :param customer_id:\n :return:\n \"\"\"\n customer_info = dict()\n try:\n with cm.database.transaction():\n customer = cm.Identity \\\n .select(cm.Identity, cm.Contact) \\\n .join(cm.Contact, JOIN.INNER) \\\n .where(cm.Contact.customer_id == customer_id) \\\n .get()\n\n customer_info['name'] = customer.name\n customer_info['lastname'] = customer.last_name\n customer_info['email_address'] = customer.contact.email_address\n customer_info['phone_number'] = customer.contact.phone_number\n\n except DoesNotExist:\n LOGGER.warning(f\"The customer ID {customer_id} does not exist in the database\")\n\n return customer_info\n\n\ndef delete_customer(customer_id):\n \"\"\"\n Deletes a customer record and all associated information\n based on the input of their customer identification number.\n :param customer_id: Customer Identification number\n :return: None\n \"\"\"\n\n try:\n with cm.database.transaction():\n customer = cm.Identity \\\n .select(cm.Identity.customer_id) \\\n .where(cm.Identity.customer_id == customer_id) \\\n .get()\n\n customer.delete_instance(recursive=True)\n LOGGER.info(\"Successfully deleted user from database.\")\n\n except DoesNotExist:\n LOGGER.warning(f\"The customer ID {customer_id} does not exist in the database\")\n raise ValueError(\"Customer ID does not exist\")\n\n\ndef update_customer_credit(customer_id, credit_limit):\n \"\"\"\n Adjusts the credit limit for a customer specified by their\n customer identification number.\n\n :param customer_id: Customer id to increase limit\n :param credit_limit: Number to adjust credit limit to\n :return:\n \"\"\"\n\n try:\n with cm.database.transaction():\n customer = (cm.Identity\n .select()\n .where(cm.Identity.customer_id == customer_id)\n .get())\n\n LOGGER.info(f\"Updating {customer.name} {customer.last_name} with credit limit {credit_limit}\")\n customer.credit_limit = credit_limit\n customer.save()\n LOGGER.info(f\"Updated {customer.name} {customer.last_name} credit limit to: {customer.credit_limit}\")\n\n except DoesNotExist:\n LOGGER.warning(f\"The customer ID {customer_id} does not exist in the database\")\n raise ValueError(\"User Does not exist\")\n\n\n\ndef list_active_customers():\n \"\"\"\n Checks the Identity table of the database and counts the number\n of active customers. Value must equal 1 in the 'active' column.\n :return: number of active customers\n \"\"\"\n try:\n with cm.database.transaction():\n active_customers = (cm.Identity\n .select()\n .where(cm.Identity.active == 1)\n .count())\n\n except Exception as e:\n LOGGER.warning(f\"Unable to determine active customers due to:\\n {e}\")\n\n return active_customers\n","sub_path":"students/mgummel/lesson03/assignment/basic_operations.py","file_name":"basic_operations.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"406510995","text":"from apps.reports import styles\n\nMONTH_NAMES = {\n 1: 'январь',\n 2: 'февраль',\n 3: 'март',\n 4: 'апрель',\n 5: 'май',\n 6: 'июнь',\n 7: 'июль',\n 8: 'август',\n 9: 'сентябрь',\n 10: 'октябрь',\n 11: 'ноябрь',\n 12: 'декабрь'\n}\n\n\ndef write_table(attendance_item, first_row, sheet):\n for i, kindergarten in enumerate(attendance_item.keys()):\n current_row = i + first_row + 1\n attendance = attendance_item[kindergarten]\n sheet.write(current_row, 0, kindergarten, styles.style)\n sheet.write(\n current_row, 1,\n attendance['children_count'],\n styles.style\n )\n sheet.write(\n current_row, 2,\n attendance['children_little_national_count'],\n styles.style\n )\n sheet.write(\n current_row, 3,\n attendance['work_days'],\n styles.style\n )\n sheet.write(\n current_row, 4,\n attendance['work_days'] * attendance['children_count'],\n styles.style\n )\n sheet.write(\n current_row, 5,\n attendance['work_days'] * attendance['children_little_national_count'],\n styles.style\n )\n\n\ndef write_table_title(sheet, row, text):\n first_column = 0\n last_column = 17\n sheet.write_merge(row, row, first_column, last_column, style=styles.group_style)\n sheet.write(row, 0, text, styles.group_style)\n","sub_path":"apps/reports/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"347644646","text":"# -*- coding: utf-8 -*-\n__author__ = 'Luke'\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom dwebsocket.decorators import accept_websocket\nfrom rest_framework.views import APIView, Response\nfrom zalo01.serializers import PhoneSerializers, OperationLogSerializers\nfrom func_timeout import func_set_timeout\nfrom Zalo.settings import redis_cache, HOST_IP\nfrom django.db.models import F\nfrom django.shortcuts import render, HttpResponse\nfrom zalo01.viewss.server_views import is_superuser\nfrom zalo01 import common, models\nfrom Zalo import rabbitMQ\nfrom Zalo.common import get_screenshot, get_phone_info_status\nimport uuid, json, time\nimport threading\n\n\nclass PhoneView(APIView):\n\n @method_decorator(login_required)\n def get(self, request):\n phone_all = models.PhoneInfo.objects.filter(userinfo=request.user)\n server_ip_dict = {}\n for phone in phone_all:\n if server_ip_dict.get(phone.server.id, None):\n continue\n server_ip_dict[phone.server.id] = phone.server.ip\n th_list = []\n for server_id, server_ip in server_ip_dict.items():\n satrt_th = threading.Thread(target=common.update_phone, args=(server_ip, server_id, []))\n th_list.append(satrt_th)\n satrt_th.start()\n for i in th_list:\n i.join()\n phone_all = models.PhoneInfo.objects.filter(userinfo=request.user).order_by(\"status\").reverse()\n phone_json_list = []\n for phone_info in phone_all:\n if phone_info.idinfo:\n phone_json_list.append(\n {\"phone_id\": phone_info.id, \"phone_name\": phone_info.phone_name,\n \"phone_status\": phone_info.status, \"phone_screenshot\": get_screenshot(phone_info),\n \"phone_info_status\": get_phone_info_status(phone_info)\n }\n )\n # 更新聊天室\n common.update_chat_room(request)\n return render(request, \"Phone/phone_index.html\",\n {\n \"nav\": \"phone\",\n \"phone_all\": phone_json_list\n }\n )\n\n @method_decorator(login_required)\n def post(self, request):\n result = {\"code\": 200, \"msg\": \"\"}\n instruct = request.data.get(\"instruct\")\n phone_id_list = request.data.get(\"phone_list\")\n if phone_id_list == \"\":\n result[\"code\"] = 401\n result[\"msg\"] = \"Vui lòng chọn 1 thiết bị để tiến hành thao tác\"\n return Response(result)\n dispose_content = common.DisposeContent(request, result)\n new_content, phone_obj_all = eval(\"dispose_content.{}()\".format(instruct))\n if result[\"code\"] != 200:\n return Response(result)\n # 根据服务器IP进行分发\n start_phone = {}\n Base_url = HOST_IP + \"static/openvpn/\"\n for phone in phone_obj_all:\n if not start_phone.get(phone.server.ip, None):\n start_phone[phone.server.ip] = []\n start_phone[phone.server.ip].append(\n {\n \"udid\": phone.udid, \"zalo_id\": phone.idinfo.code + phone.idinfo.phone,\n \"device_name\": phone.phone_name,\n \"zalo_pwd\": phone.idinfo.password, \"id\": phone.id,\n \"user_id\": request.user.id, \"app_install\": phone.app_install,\n \"open_vpn_name\": phone.OpenVpn.file_name, \"open_vpn_url\": Base_url + phone.OpenVpn.file_name,\n \"VPN_status\": phone.VPN_status, \"id_id\": phone.idinfo.id, \"zalo_status\": phone.zalo_status\n }\n )\n device_number = 0\n # 登陆验证码相关!!!!\n redis_set = \"{}_code_set\".format(request.user.id)\n over_set = \"{}_over_set\".format(request.user.id)\n user_handle_sum = \"{}_handle_sum\".format(request.user.id) # 执行设备数\n accomplish = \"{}_accomplish\".format(request.user.id) # 已完成\n redis_cache.delete(accomplish)\n redis_cache.delete(over_set)\n redis_cache.delete(redis_set)\n redis_cache.set(user_handle_sum, len(phone_obj_all))\n # 重写进度条,支持多任务进度条。\n task_name = \"{}_{}\".format(instruct, int(time.time()))\n # instruct 操作, execute_status 状态(是否开始执行 0~1)\n # progress 进度(0~100)百分比\n # device_all 设备总数, succeed_sum 执行完毕数\n # wait_time 发送进入队列时间,start_time 第一个设备执行时间, over_time 结束时间\n task_info = {\n \"instruct\": instruct, \"execute_status\": 0,\n \"progress\": 0, \"wait_time\": time.time(),\n \"start_time\": None, \"over_time\": None, \"uuid\": task_name,\n \"devices\": str([device.phone_name for device in phone_obj_all]),\n \"device_all\": len(phone_obj_all), \"succeed_device\": dict(),\n }\n redis_cache.hmset(\"{}_order\".format(request.user.username), {task_name: json.dumps(task_info)})\n print(\"开始分发\", instruct, start_phone, new_content)\n for ip, value in start_phone.items():\n queue_name = \"{}_appium\".format(ip)\n for adb in value:\n # 分发时,存入redis,执行完后更改状态,查看结果。\n key_uuid = str(uuid.uuid4())\n redis_key = \"{}_{}_{}\".format(request.user.id, adb[\"id\"], time.time())\n new_content[\"device_number\"] = device_number\n message_data = json.dumps(\n {\"instruct\": instruct, \"data\": adb, \"content\": new_content, \"redis_key\": redis_key,\n \"user\": request.user.username, \"user_id\": request.user.id, \"task_name\": task_name})\n rabbitMQ.push(queue_name, message_data, key_uuid)\n models.PhoneInfo.objects.filter(id=adb[\"id\"]).update(is_operation=1)\n device_number += 1\n return Response(result)\n\n @method_decorator(login_required)\n def put(self, request):\n pass\n\n\nclass PhoneAlterView(APIView):\n\n @method_decorator(login_required)\n def get(self, request, pk):\n lo_zalo = None\n lo_vpn = None\n phone_obj = models.PhoneInfo.objects.filter(pk=pk).first()\n device_info = {\"user_id\": \"\", \"zalo_id\": \"\", \"vpn_id\": \"\"}\n if phone_obj.userinfo:\n device_info[\"user_id\"] = str(phone_obj.userinfo.id)\n if phone_obj.idinfo:\n device_info[\"zalo_id\"] = str(phone_obj.idinfo.id)\n if phone_obj.OpenVpn:\n device_info[\"vpn_id\"] = str(phone_obj.OpenVpn.id)\n user_all = models.UserInfo.objects.filter(is_active=1)\n user_list = [{\"username\": user.username, \"id\": user.id} for user in user_all]\n vpn_list = [{\"name\": vpn.file_name, \"id\": vpn.id} for vpn in\n models.OpenVpn.objects.filter(device_max__gt=F(\"device_count\"), status=1)]\n local_vpn = models.OpenVpn.objects.filter(phoneinfo=phone_obj).first()\n if local_vpn:\n lo_vpn = {\"id\": local_vpn.id, \"name\": local_vpn.file_name}\n if lo_vpn in vpn_list:\n vpn_list.remove(lo_vpn)\n local_id = models.IdInfo.objects.filter(phoneinfo=phone_obj).first()\n zalo_list = [{\"id\": zalo.id, \"name\": zalo.name} for zalo in models.IdInfo.objects.filter(phoneinfo=None)]\n if local_id:\n lo_zalo = {\"id\": local_id.id, \"name\": local_id.name}\n if lo_zalo in zalo_list:\n zalo_list.remove(lo_zalo)\n return Response({\n \"code\": 200, \"zalo_list\": zalo_list, \"user_list\": user_list,\n \"device\": device_info, \"vpn_list\": vpn_list, \"lo_zalo\": lo_zalo,\n \"lo_vpn\": lo_vpn, \"devicename\": phone_obj.phone_name,\n })\n\n @method_decorator(login_required)\n def put(self, request, pk):\n # 如果更改了zalo账号以及vpn,则将状态对应改为2,下次执行app操作时会更新状态。\n phone_obj = models.PhoneInfo.objects.filter(pk=pk).first()\n if not request.user.is_superuser:\n if phone_obj.userinfo.id != request.user.id:\n return Response({\"code\": 403, \"msg\": \"No Access\"})\n phone_obj = models.PhoneInfo.objects.filter(pk=pk).first()\n devicename = request.data.get(\"devicename\")\n user_id = request.data.get(\"user_id\")\n zalo_id = request.data.get(\"zalo_id\")\n vpn_id = request.data.get(\"vpn_id\")\n vpn_status = request.data.get(\"vpn_status\")\n zalo_status = request.data.get(\"zalo_status\")\n # 设备状态,当这个状态为1表示正在运行,如果修改为0为造成错误,所以请务必确认手机是否在正常运行中。\n is_operation = request.data.get(\"is_operation\")\n if not phone_obj:\n return Response({\"code\": 401, \"msg\": \"The phone doesn't exist\"})\n try:\n user_id = int(user_id)\n zalo_id = int(zalo_id)\n vpn_id = int(vpn_id)\n except:\n return Response({\"code\": 401, \"msg\": \"Please enter the correct parameters\"})\n if devicename:\n if phone_obj.phone_name != devicename:\n models.PhoneInfo.objects.filter(pk=pk).update(phone_name=devicename)\n if user_id:\n if not phone_obj.userinfo:\n models.PhoneInfo.objects.filter(pk=pk).update(userinfo_id=user_id)\n elif not phone_obj.userinfo.id == user_id:\n models.PhoneInfo.objects.filter(pk=pk).update(userinfo_id=user_id)\n else:\n models.PhoneInfo.objects.filter(pk=pk).update(userinfo_id=None)\n if vpn_id:\n if not phone_obj.OpenVpn:\n models.PhoneInfo.objects.filter(pk=pk).update(OpenVpn_id=vpn_id, VPN_status=0)\n elif not phone_obj.OpenVpn.id == vpn_id:\n models.PhoneInfo.objects.filter(pk=pk).update(OpenVpn_id=vpn_id, VPN_status=2)\n else:\n models.PhoneInfo.objects.filter(pk=pk).update(OpenVpn_id=None, VPN_status=0)\n if zalo_id:\n if not phone_obj.idinfo:\n models.PhoneInfo.objects.filter(pk=pk).update(idinfo_id=zalo_id, zalo_status=0)\n elif not phone_obj.idinfo.id == zalo_id:\n models.PhoneInfo.objects.filter(pk=pk).update(idinfo_id=zalo_id, zalo_status=2)\n else:\n models.PhoneInfo.objects.filter(pk=pk).update(idinfo_id=None, zalo_status=0)\n if vpn_status:\n models.PhoneInfo.objects.filter(pk=pk).update(VPN_status=vpn_status)\n if zalo_status:\n models.PhoneInfo.objects.filter(pk=pk).update(zalo_status=zalo_status)\n if is_operation:\n models.PhoneInfo.objects.filter(pk=pk).update(is_operation=is_operation)\n return Response({\"code\": 200, \"msg\": \"successfully\"})\n\n\n@func_set_timeout(10)\ndef Get_message(request, _uid):\n res_data = rabbitMQ.pull(_uid)\n print(\"收到消息了\", res_data)\n return res_data\n\n\nclass Get_AJAX_Room(APIView):\n\n def get(self, request):\n result = {\"code\": 400}\n room_class_index = request.GET.get(\"room_class_index\")\n room_res = common.update_chat_room(request, room_class_index)\n if room_res:\n result[\"code\"] = 200\n result[\"data\"] = room_res\n else:\n result[\"msg\"] = \"更新聊天室中,请稍后重试。\"\n return Response(result)\n\n\n@accept_websocket\ndef WebSocketView(request):\n if request.is_websocket():\n print(\"%s 连接上了websocket\" % request.user.username)\n accomplish = \"{}_accomplish\".format(request.user.id)\n _uid = \"{}_mq_code\".format(request.user.id)\n redis_set = \"{}_code_set\".format(request.user.id)\n over_set = \"{}_over_set\".format(request.user.id)\n short = \"{}_short\".format(request.user.id)\n user_handle_sum = \"{}_handle_sum\".format(request.user.id)\n while True:\n try:\n time.sleep(5)\n msg = request.websocket.read()\n if msg:\n if msg.decode(\"utf8\") == \"quit\":\n request.websocket.close()\n return\n res_data = {}\n redis_cache.sdiffstore(short, redis_set, over_set)\n phone_number = redis_cache.spop(short)\n if phone_number:\n phone_number = phone_number.decode(\"utf8\")\n res_data[\"phone_number\"] = phone_number\n redis_cache.sadd(over_set, phone_number)\n res_data[\"progress_bar\"] = len(redis_cache.sinter(accomplish)) / int(\n redis_cache.get(user_handle_sum).decode(\"utf8\")) * 100\n request.websocket.send(json.dumps(res_data).encode('utf-8'))\n if res_data[\"progress_bar\"] == 100:\n request.websocket.close()\n return\n except BaseException as b:\n return\n\n\n@accept_websocket\ndef Progress_bar(request):\n if request.is_websocket():\n while True:\n try:\n _user_key = \"{}_order\".format(request.user.username)\n result = {\"record_list\": []}\n for x in redis_cache.hkeys(_user_key):\n dict_info = json.loads(redis_cache.hmget(_user_key, x.decode(\"utf8\"))[0].decode(\"utf8\"))\n if not dict_info[\"over_time\"]:\n print(dict_info)\n dict_info[\"progress\"] = round(len(dict_info[\"succeed_device\"]) / dict_info[\"device_all\"] * 100,\n 2)\n if dict_info[\"device_all\"] <= len(dict_info[\"succeed_device\"]):\n dict_info[\"over_time\"] = time.time()\n redis_cache.hmset(_user_key, {x.decode(\"utf8\"): json.dumps(dict_info)})\n result[\"record_list\"].append(dict_info)\n request.websocket.send(json.dumps(result).encode('utf-8'))\n msg = request.websocket.read()\n if msg:\n msg_info = msg.decode(\"utf8\")\n if msg_info == \"quit\":\n request.websocket.close()\n return\n # else:\n # redis_cache.hdel(_user_key, msg_info)\n time.sleep(5)\n except BaseException as b:\n print(b)\n return\n\n\nclass Code(APIView):\n\n def post(self, request):\n phone_number = request.data.get(\"phone_number\")\n code = request.data.get(\"code\")\n print(code)\n if len(code) != 4:\n return Response({\"code\": 401, \"msg\": \"Verification code error\"})\n result_json = json.dumps({\"phone_number\": phone_number, \"code\": code})\n redis_cache.set(phone_number, result_json)\n redis_cache.expire(phone_number, 120)\n return Response({\"code\": 200, \"msg\": \"Received your captcha\"})\n","sub_path":"zalo/Zalo/zalo01/viewss/phone_views.py","file_name":"phone_views.py","file_ext":"py","file_size_in_byte":15063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"248845443","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Mike\n# @Contact : 597290963@qq.com\n# @Time : 2021/2/14 9:44\n# @File : CanJump.py\nfrom typing import List\n\n\"\"\"\n给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。\n\n数组中的每个元素代表你在该位置可以跳跃的最大长度。\n\n判断你是否能够到达最后一个下标。\n\"\"\"\n\n\nclass Solution:\n\n def canJump(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return True\n if len(nums) == 0:\n return False\n\n dp = [0 for i in range(len(nums))]\n dp[0] = nums[0]\n\n for i in range(1, len(nums)):\n \"\"\"\n 判断前一个能达到的最远位置是否大于当前位置\n \"\"\"\n if dp[i - 1] < i:\n return False\n else:\n dp[i] = max(dp[i - 1], i + nums[i])\n if dp[i] >= len(nums) - 1:\n return True\n\n return False\n\n def canJump1(self, nums: List[int]) -> bool:\n \"\"\"\n 注意到 下标i只与下标i - 1有关,优化空间为O(1)\n :param nums:\n :return:\n \"\"\"\n if len(nums) == 1:\n return True\n if len(nums) == 0:\n return False\n\n max_jump = nums[0]\n for i in range(1, len(nums)):\n if max_jump < i:\n return False\n else:\n max_jump = max(max_jump, i + nums[i])\n if max_jump >= len(nums) - 1:\n return True\n\n return False","sub_path":"datastructure/dp_exercise/CanJump.py","file_name":"CanJump.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"379759931","text":"from __future__ import division\nimport numpy as np\nfrom scipy import special as sp\nimport scipy.integrate\n\n\n\n\nG = 6.67e-11\nc=3e8\n\ndef Gwaves(motion,constants):\n \n print ('Getting the waveform')\n t = motion[:,0]\n e = motion[:,1]\n g = motion[:,2]\n a = motion[:,3]\n \n M = constants[0] #total mass of inner binary\n nmodes = constants[1]\n iota = constants[2]\n mu = constants[3]\n D = constants[4]\n \n \n MA = np.sqrt(G*M) * a**(-3/2)*t #mean anomaly\n fdynamic = np.sqrt(G*M/(4*np.pi**2)) * a**(-3/2) #reparam of a to f\n omega = 2*np.pi*fdynamic\n \n\n \n #Convert to geometric units\n mu = mu * G/c**2\n M = M * G/c**2\n D = D\n omega = omega/c\n \n AA = mu/D * (M*omega)**(2/3)\n\n \n \n waveform_out = np.zeros((len(t), 3))\n waveform_out[:,0] = t \n \n \n \n \n \n for n in np.arange(1,nmodes+1):\n print ('Mode sum. n = ', n,nmodes)\n J_2 = sp.jv(n-2,n*e)\n J_1 = sp.jv(n-1,n*e) \n Jn = sp.jv(n,n*e) \n J1 = sp.jv(n+1,n*e)\n J2 = sp.jv(n+2,n*e)\n \n an = -n*AA*(J_2 - 2*e*J_1 + 2*Jn/n + 2*e*J1 - J2)*np.cos(n*MA)\n bn = -n*AA*np.sqrt((1-e**2)) * (J_2 - 2*Jn + J2)*np.sin(n*MA)\n cn = 2*AA*Jn*np.cos(n*MA)\n \n \n hplus = -(1+np.cos(iota)) * (an*np.cos(2*g) - bn*np.sin(2*g)) + (1-np.cos(iota)**2)*cn\n hcross = 2*np.cos(iota)*(bn*np.cos(2*g) + an*np.sin(2*g))\n \n waveform_out[:,1] = waveform_out[:,1] + hplus\n waveform_out[:,2] = waveform_out[:,2] + hcross\n \n\n \n \n return waveform_out\n\n\n\n\ndef overlap(data1,data2):\n \n #Get data in Fourier regime\n f1,hp1,hc1 = FT(data1)\n f2,hp2,hc2 = FT(data2)\n \n f = f1\n \n #Noise\n S = noise(f)\n \n \n \n hplusN = hp1\n hcrossN = hc1\n \n hN = np.sqrt(abs(hplusN)**2 + abs(hcrossN)**2) #numerical\n hsig1 = hN\n normN = 2 * scipy.integrate.simps( (hN * np.conj(hN) + np.conj(hN) * hN)/(S),f)\n hN = hN / np.sqrt(normN)\n #overlap = 2 * scipy.integrate.simps( (hN * np.conj(hN) + np.conj(hN) * hN)/(S),f)\n\n\n hplusA = hp2\n hcrossA = hc2\n \n hA = np.sqrt(abs(hplusA)**2 + abs(hcrossA)**2) #numerical\n hsig2 = hA\n normA = 2 * scipy.integrate.simps( (hA * np.conj(hA) + np.conj(hA) * hA)/(S),f)\n hA = hA / np.sqrt(normA)\n \n \n overlap = 2 * scipy.integrate.simps( (hN * np.conj(hA) + np.conj(hN) * hA)/(S),f)\n\n \n\n\n \n print ('overlap = ', overlap)\n \n \n return f,hsig1,hsig2, np.sqrt(S)\n\n \n \n \n \ndef FT(data): \n \n t = data[:,0]\n hplus = data[:,1]\n hcross = data[:,2]\n \n \n dt = t[1] - t[0]\n fs = 1/dt\n\n #Get the frequencies\n f = np.fft.rfftfreq(t.size,dt)\n\n \n #Take the FT\n hp = dt*np.fft.rfft(hplus)\n hc = dt*np.fft.rfft(hcross)\n \n hN =np.sqrt(abs(hp)**2 + abs(hc)**2) \n \n \n #Get rid of zeroth frequencies - WHY?\n hp = hp[1:] # get rid of zeroth frequency\n hc = hc[1:]\n f = f[1:]\n \n return f, hp, hc\n \n \n \n \n \n \ndef noise(f):\n #Calculate the LISA noise curve\n Larm = 2.5e9\n Clight = 3e8\n fstar = Clight/(2*np.pi*Larm)\n NC = 2\n\n alpha = 0.133\n beta = 243.\n kappa = 482.\n gamma = 917.\n f_knee = 2.58e-3\n\n A = 1.8e-44/NC\n Sc = 1. + np.tanh(gamma*(f_knee-f))\n Sc *=np.exp(-f**alpha + beta*f*np.sin(kappa*f))\n\n Sc *= A*f**(-7./3.)\n\n\n #LISA response function\n\n RFILE = np.loadtxt('ResponseFunction.txt')\n Rx = RFILE[:,0] * fstar\n Ry = RFILE[:,1] * NC\n\n newR = np.interp(f,Rx,Ry)\n R = newR\n\n\n #Power Spectral Density\n P_oms = (1.5e-11)**2 * (1. + (2.0e-3/f)**4)\n P_acc = (3.0e-15)**2 * (1.+(0.4e-3/f)**2)*(1. + (f/(8.0e-3))**4)\n Pn = (P_oms + 2.*(1. + np.cos(f/fstar)**2)*P_acc/(2*np.pi*f)**4)/Larm**2\n\n #Total noise\n S = Pn/R + Sc\n \n\n \n return S","sub_path":"Jupyter/Code/Revised/.ipynb_checkpoints/GravRadiation-checkpoint.py","file_name":"GravRadiation-checkpoint.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"518117646","text":"#!/usr/bin/env python\n# Read in 2D stacks for two events\n# Compute tdiff, ave_amp, amp_ratio\n# Plot radial and transverse cuts through stack, plus beam sum\n# Write out tdiff, ave_amp, amp_ratio results\n# John Vidale 3/2019\n\ndef pro6stacked_seis(eq_file1, eq_file2, plot_scale_fac = 0.03, slow_delta = 0.0005,\n\t\t\t slowR_lo = -0.1, slowR_hi = 0.1, slowT_lo = -0.1, slowT_hi = 0.1,\n\t\t\t start_buff = -50, end_buff = 50, norm = 0, freq_corr = 1.0,\n\t\t\t plot_dyn_range = 1000, fig_index = 401, get_stf = 0, ref_phase = 'blank',\n\t\t\t ARRAY = 0, max_rat = 1.8, min_amp = 0.2, turn_off_black = 0,\n\t\t\t R_slow_plot = 0, T_slow_plot = 0, tdiff_clip = 1, event_no = 0):\n\n\timport obspy\n\timport obspy.signal\n\tfrom obspy import UTCDateTime\n\tfrom obspy import Stream, Trace\n\tfrom obspy import read\n\tfrom obspy.geodetics import gps2dist_azimuth\n\timport numpy as np\n\timport os\n\tfrom obspy.taup import TauPyModel\n\timport obspy.signal as sign\n\timport matplotlib.pyplot as plt\n\tmodel = TauPyModel(model='iasp91')\n\tfrom scipy.signal import hilbert\n\timport math\n\timport time\n\timport statistics\n\n#%% Get info\n\t#%% get locations\n\tprint('Running pro6_plot_stacked_seis')\n\tstart_time_wc = time.time()\n\n\tif ARRAY == 1:\n\t\tgoto = '/Users/vidale/Documents/PyCode/LASA/EvLocs'\n\t\tos.chdir(goto)\n\n\tfile = open(eq_file1, 'r')\n\tlines=file.readlines()\n\tsplit_line = lines[0].split()\n\tt1 = UTCDateTime(split_line[1])\n\tdate_label1 = split_line[1][0:10]\n\n\tfile = open(eq_file2, 'r')\n\tlines=file.readlines()\n\tsplit_line = lines[0].split()\n\tt2 = UTCDateTime(split_line[1])\n\tdate_label2 = split_line[1][0:10]\n\n\t#%% read files\n\t# #%% Get saved event info, also used to name files\n\t# date_label = '2018-04-02' # date for filename\n\tif ARRAY == 1:\n\t\tgoto = '/Users/vidale/Documents/PyCode/LASA/Pro_files'\n\t\tos.chdir(goto)\n\tfname1 = 'HD' + date_label1 + '_2dstack.mseed'\n\tfname2 = 'HD' + date_label2 + '_2dstack.mseed'\n\tst1 = Stream()\n\tst2 = Stream()\n\tst1 = read(fname1)\n\tst2 = read(fname2)\n\n\ttshift = st1.copy() # make array for time shift\n\tamp_ratio = st1.copy() # make array for relative amplitude\n\tamp_ave = st1.copy() # make array for relative amplitude\n\n\tprint('Read in: event 1 ' + str(len(st1)) + ' event 2 ' + str(len(st2)) + ' traces')\n\tnt1 = len(st1[0].data)\n\tnt2 = len(st2[0].data)\n\tdt1 = st1[0].stats.delta\n\tdt2 = st2[0].stats.delta\n\tprint('Event 1 - First trace has ' + str(nt1) + ' time pts, time sampling of '\n\t\t + str(dt1) + ' and thus duration of ' + str((nt1-1)*dt1))\n\tprint('Event 2 - First trace has ' + str(nt2) + ' time pts, time sampling of '\n\t\t + str(dt2) + ' and thus duration of ' + str((nt2-1)*dt2))\n\tif nt1 != nt2 or dt1 != dt2:\n\t\tprint('nt or dt not does not match')\n\t\texit(-1)\n\n\t#%% Make grid of slownesses\n\tslowR_n = int(1 + (slowR_hi - slowR_lo)/slow_delta) # number of slownesses\n\tslowT_n = int(1 + (slowT_hi - slowT_lo)/slow_delta) # number of slownesses\n\tprint(str(slowT_n) + ' trans slownesses, hi and lo are ' + str(slowT_hi) + ' ' + str(slowT_lo))\n\t# In English, stack_slows = range(slow_n) * slow_delta - slow_lo\n\ta1R = range(slowR_n)\n\ta1T = range(slowT_n)\n\tstack_Rslows = [(x * slow_delta + slowR_lo) for x in a1R]\n\tstack_Tslows = [(x * slow_delta + slowT_lo) for x in a1T]\n\tprint(str(slowR_n) + ' radial slownesses, ' + str(slowT_n) + ' trans slownesses, ')\n\n#%% Loop over slowness\n\ttotal_slows = slowR_n * slowT_n\n\tglobal_max = 0\n\tfor slow_i in range(total_slows): # find envelope, phase, tshift, and global max\n\t\tif slow_i % 200 == 0:\n\t\t\tprint('At line 101, ' +str(slow_i) + ' slowness out of ' + str(total_slows))\n\t\tif len(st1[slow_i].data) == 0: # test for zero-length traces\n\t\t\t\tprint('%d data has zero length ' % (slow_i))\n\n\t\tseismogram1 = hilbert(st1[slow_i].data) # make analytic seismograms\n\t\tseismogram2 = hilbert(st2[slow_i].data)\n\n\t\tenv1 = np.abs(seismogram1) # amplitude\n\t\tenv2 = np.abs(seismogram2)\n\t\tamp_ave[slow_i].data = 0.5 * (env1 + env2)\n\t\tamp_ratio[slow_i].data = env1/env2\n\n\t\tangle1 = np.angle(seismogram1) # time shift\n\t\tangle2 = np.angle(seismogram2)\n\t\tphase1 = np.unwrap(angle1)\n\t\tphase2 = np.unwrap(angle2)\n\t\tdphase = (angle1 - angle2)\n#\t\tdphase = phase1 - phase2\n\t\tfor it in range(nt1):\n\t\t\tif dphase[it] > math.pi:\n\t\t\t\tdphase[it] -= 2 * math.pi\n\t\t\telif dphase[it] < -1 * math.pi:\n\t\t\t\tdphase[it] += 2 * math.pi\n\t\t\tif dphase[it] > math.pi or dphase[it] < -math.pi:\n\t\t\t\tprint(f'Bad dphase value {dphase[it]:.2f} {it:4d}')\n\t\tfreq1 = np.diff(phase1) #freq in radians/sec\n\t\tfreq2 = np.diff(phase2)\n\t\tave_freq = 0.5*(freq1 + freq2)\n\t\tave_freq_plus = np.append(ave_freq,[1]) # ave_freq one element too short\n#\t\ttshift[slow_i].data = dphase / ave_freq_plus # 2*pi top and bottom cancels\n\t\ttshift[slow_i].data = dphase/(2*math.pi*freq_corr)\n\n\t\tlocal_max = max(abs(amp_ave[slow_i].data))\n\t\tif local_max > global_max:\n\t\t\tglobal_max = local_max\n#%% Extract slices\n\ttshift_full = tshift.copy() # make array for time shift\n\tfor slow_i in range(total_slows): # ignore less robust points\n\t\tif slow_i % 200 == 0:\n\t\t\tprint('At line 140, ' +str(slow_i) + ' slowness out of ' + str(total_slows))\n\t\tfor it in range(nt1):\n\t\t\tif ((amp_ratio[slow_i].data[it] < (1/max_rat)) or (amp_ratio[slow_i].data[it] > max_rat) or (amp_ave[slow_i].data[it] < (min_amp * global_max))):\n\t\t\t\ttshift[slow_i].data[it] = np.nan\n\t#%% If desired, find transverse slowness nearest T_slow_plot\n\tlowest_Tslow = 1000000\n\tfor slow_i in range(slowT_n):\n\t\tif abs(stack_Tslows[slow_i] - T_slow_plot) < lowest_Tslow:\n\t\t\tlowest_Tindex = slow_i\n\t\t\tlowest_Tslow = abs(stack_Tslows[slow_i] - T_slow_plot)\n\n\tprint(str(slowT_n) + ' T slownesses, index ' + str(lowest_Tindex) + ' is closest to input parameter ' + str(T_slow_plot) + ', slowness diff there is ' + str(lowest_Tslow) + ' and slowness is ' + str(stack_Tslows[lowest_Tindex]))\n\t# Select only stacks with that slowness for radial plot\n\tcentralR_st1 = Stream()\n\tcentralR_st2 = Stream()\n\tcentralR_amp = Stream()\n\tcentralR_ampr = Stream()\n\tcentralR_tdiff = Stream()\n\tfor slowR_i in range(slowR_n):\n\t\tii = slowR_i*slowT_n + lowest_Tindex\n\t\tcentralR_st1 += st1[ii]\n\t\tcentralR_st2 += st2[ii]\n\t\tcentralR_amp += amp_ave[ii]\n\t\tcentralR_ampr += amp_ratio[ii]\n\t\tcentralR_tdiff += tshift[ii]\n\n\t#%% If desired, find radial slowness nearest R_slow_plot\n\tlowest_Rslow = 1000000\n\tfor slow_i in range(slowR_n):\n\t\tif abs(stack_Rslows[slow_i] - R_slow_plot) < lowest_Rslow:\n\t\t\tlowest_Rindex = slow_i\n\t\t\tlowest_Rslow = abs(stack_Rslows[slow_i] - R_slow_plot)\n\n\tprint(str(slowR_n) + ' R slownesses, index ' + str(lowest_Rindex) + ' is closest to input parameter ' + str(R_slow_plot) + ', slowness diff there is ' + str(lowest_Rslow) + ' and slowness is ' + str(stack_Rslows[lowest_Rindex]))\n\n\t# Select only stacks with that slowness for transverse plot\n\tcentralT_st1 = Stream()\n\tcentralT_st2 = Stream()\n\tcentralT_amp = Stream()\n\tcentralT_ampr = Stream()\n\tcentralT_tdiff = Stream()\n\n\t#%% to extract stacked time functions\n\tevent1_sample = Stream()\n\tevent2_sample = Stream()\n\n\tfor slowT_i in range(slowT_n):\n\t\tii = lowest_Rindex*slowT_n + slowT_i\n\t\tcentralT_st1 += st1[ii]\n\t\tcentralT_st2 += st2[ii]\n\t\tcentralT_amp += amp_ave[ii]\n\t\tcentralT_ampr += amp_ratio[ii]\n\t\tcentralT_tdiff += tshift[ii]\n\n\t#%% compute timing time series\n\tttt = (np.arange(len(st1[0].data)) * st1[0].stats.delta + start_buff) # in units of seconds\n\n#%% Plot radial amp and tdiff vs time plots\n\tfig_index = 6\n#\tplt.close(fig_index)\n\tplt.figure(fig_index,figsize=(30,10))\n\tplt.xlim(start_buff,end_buff)\n\tplt.ylim(stack_Rslows[0], stack_Rslows[-1])\n\tfor slowR_i in range(slowR_n): # loop over radial slownesses\n\t\tdist_offset = stack_Rslows[slowR_i] # trying for approx degrees\n\t\tttt = (np.arange(len(centralR_st1[slowR_i].data)) * centralR_st1[slowR_i].stats.delta\n\t\t + (centralR_st1[slowR_i].stats.starttime - t1))\n\t\tplt.plot(ttt, (centralR_st1[slowR_i].data - np.median(centralR_st1[slowR_i].data))*plot_scale_fac /global_max + dist_offset, color = 'green')\n\t\tplt.plot(ttt, (centralR_st2[slowR_i].data - np.median(centralR_st2[slowR_i].data))*plot_scale_fac /global_max + dist_offset, color = 'red')\n\t\t# extract stacked time functions\n\t\tif get_stf != 0:\n\t\t\tif np.abs(stack_Rslows[slowR_i]- 0.005) < 0.000001: # kludge, not exactly zero when desired\n\t\t\t\tevent1_sample = centralR_st1[slowR_i].copy()\n\t\t\t\tevent2_sample = centralR_st2[slowR_i].copy()\n#\t\tplt.plot(ttt, (centralR_amp[slowR_i].data) *plot_scale_fac/global_max + dist_offset, color = 'purple')\n\t\tif turn_off_black == 0:\n\t\t\tplt.plot(ttt, (centralR_tdiff[slowR_i].data)*plot_scale_fac/1 + dist_offset, color = 'black')\n\t\t\tplt.plot(ttt, (centralR_amp[slowR_i].data)*0.0 + dist_offset, color = 'lightgray') # reference lines\n\tplt.xlabel('Time (s)')\n\tplt.ylabel('R Slowness (s/km)')\n\tplt.title(ref_phase + ' seismograms and tdiff at ' + str(T_slow_plot) + ' T slowness, green is event1, red is event2')\n\t# Plot transverse amp and tdiff vs time plots\n\tfig_index = 7\n#\tplt.close(fig_index)\n\tplt.figure(fig_index,figsize=(30,10))\n\tplt.xlim(start_buff,end_buff)\n\tplt.ylim(stack_Tslows[0], stack_Tslows[-1])\n\n\tfor slowT_i in range(slowT_n): # loop over transverse slownesses\n\t\tdist_offset = stack_Tslows[slowT_i] # trying for approx degrees\n\t\tttt = (np.arange(len(centralT_st1[slowT_i].data)) * centralT_st1[slowT_i].stats.delta\n\t\t + (centralT_st1[slowT_i].stats.starttime - t1))\n\t\tplt.plot(ttt, (centralT_st1[slowT_i].data - np.median(centralT_st1[slowT_i].data))*plot_scale_fac /global_max + dist_offset, color = 'green')\n\t\tplt.plot(ttt, (centralT_st2[slowT_i].data - np.median(centralT_st2[slowT_i].data))*plot_scale_fac /global_max + dist_offset, color = 'red')\n#\t\tplt.plot(ttt, (centralT_amp[slowT_i].data) *plot_scale_fac/global_max + dist_offset, color = 'purple')\n\t\tif turn_off_black == 0:\n\t\t\tplt.plot(ttt, (centralT_tdiff[slowT_i].data)*plot_scale_fac/1 + dist_offset, color = 'black')\n\t\t\tplt.plot(ttt, (centralT_amp[slowT_i].data)*0.0 + dist_offset, color = 'lightgray') # reference lines\n\tplt.xlabel('Time (s)')\n\tplt.ylabel('T Slowness (s/km)')\n\tplt.title(str(event_no) + ' ' + date_label1 + ' ' +ref_phase + ' seismograms and tdiff ' + str(R_slow_plot) + ' R slowness, green is event1, red is event2')\n\tos.chdir('/Users/vidale/Documents/PyCode/LASA/Quake_results/Plots')\n#\tplt.savefig(date_label1 + '_' + str(start_buff) + '_' + str(end_buff) + '_stack.png')\n\n#%% R-T tshift averaged over time window\n\tfig_index = 8\n\tstack_slice = np.zeros((slowR_n,slowT_n))\n\tfor slowR_i in range(slowR_n): # loop over radial slownesses\n\t\tfor slowT_i in range(slowT_n): # loop over transverse slownesses\n\t\t\tindex = slowR_i*slowT_n + slowT_i\n\t\t\tnum_val = np.nanmedian(tshift[index].data)\n#\t\t\tnum_val = statistics.median(tshift_full[index].data)\n\t\t\tstack_slice[slowR_i, slowT_i] = num_val # adjust for dominant frequency of 1.2 Hz, not 1 Hz\n#\tstack_slice[0,0] = -0.25\n#\tstack_slice[0,1] = 0.25\n#\ttdiff_clip = 0.4/1.2\n\ttdiff_clip_max = tdiff_clip # DO NOT LEAVE COMMENTED OUT!!\n\ttdiff_clip_min = -tdiff_clip\n\n\ty1, x1 = np.mgrid[slice(stack_Rslows[0], stack_Rslows[-1] + slow_delta, slow_delta),\n\t\t\t\t slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta)]\n\n\tfig, ax = plt.subplots(1, figsize=(7,6))\n#\t\tfig, ax = plt.subplots(1, figsize=(9,2))\n#\t\tfig.subplots_adjust(bottom=0.3)\n#\tc = ax.pcolormesh(x1, y1, stack_slice, cmap=plt.cm.bwr, vmin = tdiff_clip_min, vmax = tdiff_clip_max)\n\tc = ax.pcolormesh(x1, y1, stack_slice, cmap=plt.cm.coolwarm, vmin = tdiff_clip_min, vmax = tdiff_clip_max)\n\tax.axis([x1.min(), x1.max(), y1.min(), y1.max()])\n\tcircle1 = plt.Circle((0, 0), 0.019, color='black', fill=False)\n\tax.add_artist(circle1)\n\tcircle2 = plt.Circle((0, 0), 0.040, color='black', fill=False)\n\tax.add_artist(circle2) #outer core limit\n\tfig.colorbar(c, ax=ax)\n\tplt.ylabel('R Slowness (s/km)')\n\tplt.title(ref_phase + ' time shift')\n#\tplt.title('T-R average time shift ' + date_label1 + ' ' + date_label2)\n\tplt.show()\n\n#%% R-T amplitude averaged over time window\n\tfig_index = 9\n\tstack_slice = np.zeros((slowR_n,slowT_n))\n\tsmax = 0\n\tfor slowR_i in range(slowR_n): # loop over radial slownesses\n\t\tfor slowT_i in range(slowT_n): # loop over transverse slownesses\n\t\t\tindex = slowR_i*slowT_n + slowT_i\n\t\t\tnum_val = np.nanmedian(amp_ave[index].data)\n\t\t\tstack_slice[slowR_i, slowT_i] = num_val\n\t\t\tif num_val > smax:\n\t\t\t\tsmax = num_val\n#\tstack_slice[0,0] = 0\n\n\ty1, x1 = np.mgrid[slice(stack_Rslows[0], stack_Rslows[-1] + slow_delta, slow_delta),\n\t\t\t\t slice(stack_Tslows[0], stack_Tslows[-1] + slow_delta, slow_delta)]\n\n#\tfig, ax = plt.subplots(1)\n\tfig, ax = plt.subplots(1, figsize=(7,6))\n#\tc = ax.pcolormesh(x1, y1, stack_slice/smax, cmap=plt.cm.gist_yarg, vmin = 0.5)\n\tc = ax.pcolormesh(x1, y1, stack_slice/smax, cmap=plt.cm.gist_rainbow_r, vmin = 0)\n#\tc = ax.pcolormesh(x1, y1, stack_slice, cmap=plt.cm.gist_rainbow_r, vmin = 0)\n\tax.axis([x1.min(), x1.max(), y1.min(), y1.max()])\n\tcircle1 = plt.Circle((0, 0), 0.019, color='black', fill=False)\n\tax.add_artist(circle1) #inner core limit\n\tcircle2 = plt.Circle((0, 0), 0.040, color='black', fill=False)\n\tax.add_artist(circle2) #outer core limit\n\tfig.colorbar(c, ax=ax)\n\tplt.xlabel('Transverse Slowness (s/km)')\n\tplt.ylabel('Radial Slowness (s/km)')\n\tplt.title(ref_phase + ' beam amplitude')\n#\tplt.title('Beam amplitude ' + date_label1 + ' ' + date_label2)\n\tos.chdir('/Users/vidale/Documents/PyCode/LASA/Quake_results/Plots')\n\tplt.savefig(date_label1 + '_' + str(start_buff) + '_' + str(end_buff) + '_beam.png')\n\tplt.show()\n\n#%% Save processed files\n\tif ARRAY == 0:\n\t\tgoto = '/Users/vidale/Documents/PyCode/Hinet'\n\tif ARRAY == 1:\n\t\tgoto = '/Users/vidale/Documents/PyCode/LASA/Pro_Files'\n\tos.chdir(goto)\n\n\tfname = 'HD' + date_label1 + '_' + date_label2 + '_tshift.mseed'\n\ttshift_full.write(fname,format = 'MSEED')\n\n\tfname = 'HD' + date_label1 + '_' + date_label2 + '_amp_ave.mseed'\n\tamp_ave.write(fname,format = 'MSEED')\n\n\tfname = 'HD' + date_label1 + '_' + date_label2 + '_amp_ratio.mseed'\n\tamp_ratio.write(fname,format = 'MSEED')\n\n#%% Option to write out stf\n\tif get_stf != 0:\n\t\tevent1_sample.taper(0.1)\n\t\tevent2_sample.taper(0.1)\n\t\tfname = 'HD' + date_label1 + '_stf.mseed'\n\t\tevent1_sample.write(fname,format = 'MSEED')\n\t\tfname = 'HD' + date_label2 + '_stf.mseed'\n\t\tevent2_sample.write(fname,format = 'MSEED')\n\n\telapsed_time_wc = time.time() - start_time_wc\n\tprint('This job took ' + str(elapsed_time_wc) + ' seconds')\n\tos.system('say \"Done\"')\n","sub_path":"pro6_plot_stacked_seis_copy.py","file_name":"pro6_plot_stacked_seis_copy.py","file_ext":"py","file_size_in_byte":14292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"246440109","text":"from __future__ import print_function\nimport ROOT as rt\nimport root_numpy\nimport pickle\nimport argparse\nimport os\nimport sys\nimport shutil\nimport numpy as np\nimport logging\n\n\n\"\"\"\npython tree_to_np.py [files and/or directories to be converted] \n -d [destination of resulting numpy arrays] \n -n [path to the connected np array]\n -c [True/False clean (remove) the directory of concatenate files]\npython tree_to_np.py source1 -d ./ -name_conn conn.pkl -clean True\n\npython2.7 tree_to_np.py /eos/cms/store/user/fsiroky/data_fifthrun/ -d=/eos/cms/store/group/comm_dqm/cmsml4dc/2016-v1/data2016_v2\n\n\"\"\"\n\ndef convert_tree_to_np(sources, destination, npy_files=[]):\n \"\"\" Converts the root files in sources to numpy arrays\n Params\n sources : list\n root file paths/names or path to directory of root files\n destination : str\n path to directory where the npy files will be saved\n npy_files : list\n list of already converted files (for recursive functionality)\n Returns\n list\n paths to the converted files \n \"\"\"\n for i in xrange(len(sources)):\n if os.path.isdir(sources[i]) and ('failed' not in sources[i]):\n # source is a directory -> recurse on all files in directory\n new_sources = [sources[i]+'/'+e for e in os.listdir(sources[i])]\n new_destination = destination+'/'+sources[i].split('/')[-1]\n\n print('new_sources ', len(new_sources), new_sources[-9:])\n print('new_destination ', new_destination)\n logging.info('new_sources '+ str(len(new_sources))+' '+ str(new_sources[-9:]))\n logging.info('new_destination '+ new_destination)\n os.mkdir(new_destination)\n convert_tree_to_np(new_sources, new_destination, npy_files)\n else:\n if \".root\" in sources[i]:\n try:\n # print(i, sources[i])\n logging.info(str(i) +' '+ sources[i])\n print(str(i)+' ', end=\"\")\n sys.stdout.flush()\n\n tChain = rt.TChain('MyAnalysis/MyTree')\n tChain.Add(sources[i])\n\n array = root_numpy.tree2array(tChain)\n # print 'Total number of entries: ',tChain.GetEntries()\n \n pkl_file_name = destination+'/'+sources[i].split('/')[-1][:-5]\n np.save(pkl_file_name, array)\n npy_files.append(pkl_file_name+'.npy')\n except Exception as e:\n if os.path.exists('failed.pkl'):\n continue\n else:\n mylist=[]\n with open('failed.pkl', 'wb') as f:\n pickle.dump(mylist, f)\n print(\"\")\n print(e)\n print(sources[i], \" ** FAILED ** \")\n logging.error(sources[i]+ \" ** FAILED ** \")\n logging.error(e)\n\n f = open('failed.pkl', 'rb')\n failed = pickle.load(f)\n f.close()\n failed.append(sources[i])\n f = open('failed.pkl', 'wb')\n pickle.dump(failed, f)\n f.close()\n \n \n\n return npy_files\n\ndef concatenate_pickles(npy_files, name_conn, clean=False, sources=[], destination=\"./\"):\n \"\"\"Concatenate numpy arrays in multiple files into one numpy array and saves it.\n Params\n npy_files : list\n paths to np arrays\n name_conn : str\n path to the concatenated np array (destination)\n Returns\n void\n \"\"\"\n # loading the first array\n array = np.load(npy_files[0])\n for npy_file_name in npy_files[1:]:\n print(npy_file_name)\n next_array = np.load(npy_file_name)\n \n array = np.concatenate((array, next_array), axis=0)\n\n np.save(name_conn, array)\n\n if clean:\n # removes the directory of unconcatenated npy files\n for i in xrange(len(sources)):\n if os.path.isdir(sources[i]):\n shutil.rmtree(destination+'/'+sources[i].split('/')[-1])\n\n\ndef main():\n logging.basicConfig(filename='tree_to_np.log',level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M')\n parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')\n parser.add_argument( dest='sources', metavar='N', type=str, nargs='+', help='Help sources') #'-s', '--sources',\n parser.add_argument(\"-d\", \"--destination\", dest=\"destination\", default=\"./\", help=\"Help destination\")\n parser.add_argument(\"-n\", \"-name_conn\", dest=\"name_conn\", default=\"\", help=\"Help name_conn\")\n parser.add_argument(\"-c\", \"-clean\", dest=\"clean\", default=False, help=\"Help clean\")\n args = parser.parse_args()\n\n print(args)\n sources = args.sources\n destination = args.destination\n name_conn = args.name_conn\n clean = not( args.clean=='False' )\n\n npy_files = convert_tree_to_np(sources, destination)\n print(npy_files)\n logging.info(str(npy_files))\n\n if name_conn:\n concatenate_pickles(npy_files, name_conn, clean=clean, sources=sources, destination=destination)\n\n\nif __name__ == '__main__':\n main()\n print(\"tree_to_np DONE\")\n\n\n","sub_path":"rt_np_test/tree_to_np.py","file_name":"tree_to_np.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"430182017","text":"# Import so that the bot could function\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\nimport time\nimport random\nfrom random import randint\nimport Config\nimport datetime\nimport asyncio\nimport discord\nimport os\nfrom discord.ext.commands import Bot\n\n#Determine the bots prefix\nbot = commands.Bot(command_prefix = Config.PREFIX)\n\n@bot.event\nasync def on_ready():\n print(\"===================================\")\n print(\"Logged in as: %s\"%bot.user.name)\n print(\"ID: %s\"%bot.user.id)\n print('Server count:', str(len(bot.servers)))\n print('User Count:',len(set(bot.get_all_members())))\n print(\"Py Lib Version: %s\"%discord.__version__)\n print(\"===================================\")\n\n@bot.command(pass_context = True)\nasync def rules(ctx):\n\t\tembed = discord.Embed(title=\"Welcome To The Official SkiGang Discord Server!\", colour=discord.Colour(0xea821a), timestamp=datetime.datetime.utcfromtimestamp(1547283256))\n\n\t\tembed.set_thumbnail(url=\"https://i.imgur.com/hYceQ6F.jpg\")\n\n\t\tembed.add_field(name=\"Rules\", value=\"1. Do NOT Spam Music unless allowed, or in a music only channel.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"2. Do NOT impersonate anyone.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"3. Do NOT spam any chats.\", inline = False)\n\t\tembed.add_field(name=\"\\u200B\", value=\"4. No trolling, at least keep it to a minimum :wink:\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"5. No Channel hopping. Channel hopping is defined as switching channels in quick succession for either positive or negative purposes.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"6. No glitching of any kind, or attempting to gain control of permissions through dishonest means.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"7. No Innappropriate pictures/porn pics in any chat other than #nsfw-💀\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"8. Be respectful to all users/staff.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"9. No spamming staff for roles/ranks.\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"10. Have a fun time and enjoy your stay!\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name = \"------------Support Rules/HowTo------------\", value = \"If you have any questions about the discord server or about your Garry's Mod server please see the #support-🎫 channel and use the command -new YOURQUESTION\", inline = False)\n\t\tembed.add_field(name = \"\\u200B\", value = \"DO NOT ASK FOR SUPPORT IN GENERAL CHAT... ONLY #support-🎫 CHAT\", inline = True)\n\t\tembed.add_field(name = \"--------------------END--------------------\", value = \"\\u200B\", inline = True)\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\t\tembed.add_field(name=\"\\u200B\", value=\"\\u200B\")\n\n\t\tawait bot.say(content=\"\", embed=embed)\n\t\t\n@bot.command(pass_context = True)\nasync def support(ctx):\n\t\tembed = discord.Embed(title=\"Discord Support HowTo\", colour=discord.Colour(0xea821a), timestamp=datetime.datetime.utcfromtimestamp(1547283256))\n\n\t\tembed.set_thumbnail(url=\"https://i.imgur.com/hYceQ6F.jpg\")\n\t\t\n\t\tembed.add_field(name=\"Commands\", value=\"To create a ticket please use the command -new YOURQUESTION\")\n\t\tembed.add_field(name=\"Please give all support staff time to read and respond to each problem/question thanks.\", value=\"\\u200B\")\n\n\t\tawait bot.say(content=\"\", embed=embed)\n \nclient.run(os.getenv('TOKEN'))\n","sub_path":"skibot.py","file_name":"skibot.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"583121753","text":"from inspect import getgeneratorstate\n\n\ndef is_even_number():\n value = yield\n\n # запускаем безсконечный генератор (unbound generator)\n while True:\n\n if value % 2:\n result = False\n else:\n result = True\n\n value = yield result\n\n\ndef main():\n print('*' * 80)\n a = 3\n b = 4\n\n # создаем генератор\n even_number_checker = is_even_number()\n\n print(str.format(\n '[*] even_number_checker (created) state: {}',\n getgeneratorstate(even_number_checker)\n ))\n\n # запускае (prime) генератор\n even_number_checker.send(None)\n\n print(str.format(\n '[*] even_number_checker (primed) state: {}',\n getgeneratorstate(even_number_checker)\n ))\n\n print('-' * 80)\n\n # отправляем значение в объект генератор\n a_is_even = even_number_checker.send(a)\n print(str.format('[*] {} is even: {}', a, a_is_even))\n\n print('-' * 80)\n\n # отправляем значение в объект генератор\n b_is_even = even_number_checker.send(b)\n print(str.format('[*] {} is even: {}', b, b_is_even))\n\n # закрываем бесконенчный генератор\n even_number_checker.close()\n\n # закрытый генератор не может принимать значения\n try:\n even_number_checker.send(23)\n except StopIteration:\n pass\n\n print('-' * 80)\n\n print(str.format(\n '[*] even_number_checker (closed) state: {}',\n getgeneratorstate(even_number_checker)\n ))\n\n print('-' * 80)\n\n # создаем новый генератор проверки четных чисел\n yac = is_even_number()\n yac.send(None)\n\n # создаем выражение генератора, которое предоставляет числа, кратные 2 и 7\n even_number_divided_by_seven = (\n even_number for even_number in range(1, 101) if\n yac.send(even_number) is True\n and even_number % 7 == 0\n )\n\n [print(str.format(\n '[*] value: {}', value), end=str.format('\\n{}\\n', '-' * 40)\n ) for value in even_number_divided_by_seven]\n\n print('-' * 80)\n\n print('*' * 80)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"core/builtin_features/generators/generator_function/gen_extended_unbound.py","file_name":"gen_extended_unbound.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"417037579","text":"import requests\nfrom bs4 import BeautifulSoup\nimport bs4\n\ndef getHTMLText(url):\n try:\n r = requests.get(url , timeout = 30)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n return r.text\n except:\n print(\"error\")\n\n\ndef fillUiveList(ulist,html):\n soup = BeautifulSoup(html , \"html.parser\")\n for tr in soup.find(\"tbody\").children:\n if isinstance(tr , bs4.element.Tag):\n tds = tr(\"td\")\n ulist.append([tds[0].string , tds[1].string , tds[2].string])\n\n\ndef printUniveList(ulist,num):\n print(\"{:^10}\\t{:^6}\".format(\"排名\" , \"学校\" ))\n for i in range(num):\n item = ulist[i]\n print(\"{:^10}\\t{:^6}\".format(item[0],item[1]))\n\ndef main():\n uinfo = []\n url = \"http://www.zuihaodaxue.cn/ARWU2018.html\"\n html = getHTMLText(url)\n fillUiveList(uinfo , html)\n printUniveList(uinfo , 20)\n\nif __name__ == '__main__':\n main()","sub_path":"Boss/Request/University.py","file_name":"University.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"289181339","text":"import time\nfrom pageobjects.environments import Environments\nfrom pageobjects.nodes import Nodes, RolesPanel\nfrom tests import preconditions\nfrom tests.base import BaseTestCase\n\nERROR_ROLE_CANNOT_COMBINE = 'This role cannot be combined ' \\\n 'with the other roles already selected.'\nROLE_UNALLOCATED = 'UNALLOCATED'\nROLE_CONTROLLER = 'CONTROLLER'\nROLE_COMPUTE = 'COMPUTE'\nROLE_CINDER = 'CINDER'\nROLE_CEPH = 'CEPH-OSD'\n\n\nclass BaseClass(BaseTestCase):\n\n def assertNodeInRoles(self, node, roles):\n for role in roles:\n self.assertIn(role, node.roles.text, \"node's roles\")\n\n def setUp(self):\n BaseTestCase.setUp(self)\n Environments().create_cluster_boxes[0].click()\n Nodes().add_nodes.click()\n time.sleep(1)\n\n\nclass TestRolesSimpleFlat(BaseClass):\n\n @classmethod\n def setUpClass(cls):\n BaseTestCase.setUpClass()\n preconditions.Environment.simple_flat()\n\n def test_controller(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.controller.click()\n self.assertFalse(r.compute.is_enabled())\n self.assertIn(\n ERROR_ROLE_CANNOT_COMBINE,\n r.compute.find_element_by_xpath('../..').text,\n 'error \"{}\" is visible'.format(ERROR_ROLE_CANNOT_COMBINE))\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_CONTROLLER])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_one_controller_allowed_nodes_disabled(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.controller.click()\n for n in Nodes().nodes_discovered[1:]:\n self.assertFalse(\n n.checkbox.find_element_by_tag_name('input').is_enabled(),\n 'Checkbox is disabled')\n\n def test_one_controller_allowed_controller_role_disabled(self):\n with Nodes()as n:\n with RolesPanel() as r:\n n.nodes_discovered[0].checkbox.click()\n self.assertTrue(r.controller.is_enabled())\n for node in n.nodes_discovered[1:]:\n node.checkbox.click()\n self.assertFalse(r.controller.is_enabled())\n\n def test_compute(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.compute.click()\n self.assertFalse(r.controller.is_enabled())\n self.assertIn(\n ERROR_ROLE_CANNOT_COMBINE,\n r.controller.find_element_by_xpath('../..').text,\n 'error \"{}\" is visible'.format(ERROR_ROLE_CANNOT_COMBINE))\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_COMPUTE])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_cinder(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.cinder.click()\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_CINDER])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_ceph(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.ceph_osd.click()\n with Nodes()as n:\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_CEPH])\n self.assertTrue(n.apply_changes.is_enabled())\n n.nodes_discovered[0].checkbox.click()\n self.assertFalse(n.apply_changes.is_enabled())\n self.assertNodeInRoles(n.nodes_discovered[0], [ROLE_UNALLOCATED])\n\n def test_multiroles(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n with RolesPanel() as r:\n r.controller.click()\n r.cinder.click()\n r.ceph_osd.click()\n with Nodes()as n:\n self.assertNodeInRoles(\n n.nodes_discovered[0],\n [ROLE_CONTROLLER, ROLE_CINDER, ROLE_CEPH])\n\n def test_several_nodes(self):\n with Nodes()as n:\n n.nodes_discovered[0].checkbox.click()\n n.nodes_discovered[1].checkbox.click()\n n.nodes_discovered[2].checkbox.click()\n with RolesPanel() as r:\n r.compute.click()\n r.cinder.click()\n r.ceph_osd.click()\n with Nodes()as n:\n self.assertNodeInRoles(\n n.nodes_discovered[0],\n [ROLE_COMPUTE, ROLE_CINDER, ROLE_CEPH])\n self.assertNodeInRoles(\n n.nodes_discovered[1],\n [ROLE_COMPUTE, ROLE_CINDER, ROLE_CEPH])\n self.assertNodeInRoles(\n n.nodes_discovered[2],\n [ROLE_COMPUTE, ROLE_CINDER, ROLE_CEPH])\n\n\nclass TestRolesHAFlat(BaseClass):\n\n @classmethod\n def setUpClass(cls):\n BaseTestCase.setUpClass()\n preconditions.Environment.ha_flat()\n\n def test_controller_role_always_enabled(self):\n with Nodes()as n:\n for node in n.nodes_discovered:\n node.checkbox.click()\n self.assertTrue(RolesPanel().controller.is_enabled())\n RolesPanel().controller.click()\n for node in n.nodes_discovered:\n self.assertNodeInRoles(node, [ROLE_CONTROLLER])\n\n def test_all_nodes_could_be_controller(self):\n RolesPanel().controller.click()\n with Nodes()as n:\n for node in n.nodes_discovered:\n node.checkbox.click()\n for node in n.nodes_discovered:\n self.assertNodeInRoles(node, [ROLE_CONTROLLER])\n","sub_path":"fuelweb_ui_test/tests/test_roles.py","file_name":"test_roles.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"578538016","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport numpy as np\n\nlis = []\n\nstructs_params = np.load('/home/chengch/NMA/data/10W/data/struct_params.npy')\nstructs_aligned = np.load('/home/chengch/NMA/data/10W/data/structs_aligned.npy')\nIR = np.load('/home/chengch/NMA/data/10W/data/IR.npy')\ndata = structs_params[:,16]\ndata = abs(data)\n\n#this si making the split_number for all data\nstruct1 =[]\nstruct2= []\nstruct3 = []\nstruct4 = []\nfor _, x in enumerate(data):\n lis.append((_,x)) \n\nfor _ in lis:\n if 170 < _[1] <= 180:\n struct1.append(_)\n elif 160 < _[1] <= 170:\n struct2.append(_)\n elif 150 < _[1] <= 160:\n struct3.append(_)\n elif 140 < _[1] <= 150:\n struct4.append(_)\n\n#this is split the struct_params to 140-150, 150-160, 160-170, 170-180, 160-180\nstruct_params1 =[]\nstruct_params2 = []\nstruct_params3 = []\nstruct_params4 = []\n\nfor _ in struct1:\n struct_params1.append(structs_params[_[0]])\nfor _ in struct2:\n struct_params2.append(structs_params[_[0]])\nfor _ in struct3:\n struct_params3.append(structs_params[_[0]])\nfor _ in struct4:\n struct_params4.append(structs_params[_[0]]) \n\n#\nnp.save('struct_params1.npy',struct_params1)\nnp.save('struct_params2.npy',struct_params2)\nnp.save('struct_params3.npy',struct_params3)\nnp.save('struct_params4.npy',struct_params4)\n#160-180\nfor _ in struct2:\n struct_params1.append(structs_params[_[0]])\nnp.save('struct_params1_2.npy',struct_params1)\n\nprint ('_____________struct_params finished_____________')\n#this is split the IR to 140-150, 150-160, 160-170, 170-180, 160-180\nIR1 = []\nIR2 = [] \nIR3 = []\nIR4 = [] \n\nfor _ in struct1:\n IR1.append(IR[_[0]])\nfor _ in struct2:\n IR2.append(IR[_[0]])\nfor _ in struct3:\n IR3.append(IR[_[0]])\nfor _ in struct4:\n IR4.append(IR[_[0]]) \n\nnp.save('IR1.npy',IR1)\nnp.save('IR2.npy',IR2)\nnp.save('IR3.npy',IR3)\nnp.save('IR4.npy',IR4)\n#160-180\nfor _ in struct2:\n IR1.append(IR[_[0]])\nnp.save('IR1_2.npy',IR1)\nprint ('_____________IR finished_____________')\n\nstruct_aligned1 = []\nstruct_aligned2 = []\nstruct_aligned3 = []\nstruct_aligned4 = []\n\nfor _ in struct1:\n struct_aligned1.append(structs_aligned[_[0]])\nfor _ in struct2:\n struct_aligned2.append(structs_aligned[_[0]])\nfor _ in struct3:\n struct_aligned3.append(structs_aligned[_[0]])\nfor _ in struct4:\n struct_aligned4.append(structs_aligned[_[0]])\n\nnp.save('struct_aligned1.npy',struct_aligned1)\nnp.save('struct_aligned2.npy',struct_aligned2)\nnp.save('struct_aligned3.npy',struct_aligned3)\nnp.save('struct_aligned4.npy',struct_aligned4)\n\nfor _ in struct2:\n struct_aligned1.append(structs_aligned[_[0]])\n\nnp.save('struct_aligned1_2.npy',struct_aligned1)\n","sub_path":"data_wash_copy.py","file_name":"data_wash_copy.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"491787881","text":"import numpy\nimport scipy.linalg\n\n# as column vector\nP0b = numpy.matrix([[0.33, 0.33, 0.34]])\n\nQb = numpy.matrix([[-0.21, 0.2, 0.01],\n [ 0.05, -0.1, 0.05],\n [ 0.01, 0.2, -0.21]])\n\nMb = numpy.matrix([[0.21, 0, 0 ],\n [0, 0.1, 0 ],\n [0, 0, 0.21]])\n\nPEb = numpy.matrix([[ 0, 20./21., 1./21.],\n [ 1./2., 0, 1./2. ],\n [20./21., 1./21., 0 ]])\n\nPEb_corrected = numpy.matrix([[ 0, 20./21., 1./21.],\n [ 1./2., 0, 1./2. ],\n [ 1./21., 20./21., 0 ]])\n\nUSb = numpy.matrix([[-0.1, 0.05],\n [ 0.2, -0.21]])\n\ndef Q_from_M_PE(M, PE):\n return M * (PE - numpy.eye(M.shape[0]))\n\ndef p_t_given_s(Qx, t, s):\n return numpy.asmatrix(scipy.linalg.expm(Qx * (t - s)))\n\ndef p_t(Qx, Px0, t):\n return Px0 * scipy.linalg.expm(Qx * t)\n\n#----------------------------------\n\ndef barometric_example_subsystem_dist(t):\n entrance_dist = numpy.matrix([0.5, 0.5])\n S_intensity = numpy.matrix([[-0.1, 0.05],\n [ 0.2, -0.21]])\n expS = scipy.linalg.expm(S_intensity * t)\n e = numpy.asmatrix(numpy.ones(entrance_dist.shape[0])).T\n return 1 - entrance_dist * expS * e\n\ndef barometric_example_subsystem_dist_direct(t):\n \"\"\" Example 2.4: distribution in time over when the pressure begins to fall. \"\"\"\n return 1 - 1.0476*pow(0.960,t) + 0.0476*pow(0.7641,t)\n\n","sub_path":"sandbox/clayton/ctbn.py","file_name":"ctbn.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"552536440","text":"import sys\nimport subprocess\nimport re\n\nfrom PySide import QtGui\nfrom PySide import QtCore\nfrom PySide.QtWebKit import QWebView, QWebSettings\n\nnotif_h = 230\nnotif_w = 250\nnotif_x = 100\nnotif_y = 100\n\ndef scan(view):\n\twindow = subprocess.Popen([\"xdotool\", \"getactivewindow\"],stdout=subprocess.PIPE)\n\twindow_id = window.communicate()[0].strip(\"\\n\")\n\twindow_inf=subprocess.Popen([\"xwininfo\", \"-id\" ,window_id],stdout=subprocess.PIPE)\n\twindow_info = window_inf.communicate()[0].strip(\"\\n\")\n\t#print window_info\n\n\tgeometry = re.findall(\"\\\"([\\s\\S]*)\\\"[\\s\\S]*Absolute upper-left X:\\s*(-*\\d+)\\s*Absolute upper-left Y:\\s*(-*\\d+)[\\s\\S]*Width:\\s*(\\d+)\\s*Height:\\s*(\\d+)\",\n\t\t\t\t\t\t\twindow_info)\n\n\t#print geometry\n\n\t#if not view.isActiveWindow():\n\tif view.x() != int(geometry[0][1]) and view.y() != int(geometry[0][2]):\n\t\tview.setGeometry(int(geometry[0][1])+int(geometry[0][3]),int(geometry[0][2]),notif_w,notif_h)\n\t\tview.raise_()\n\n\treturn 0\n\n\nclass MainWindow(QtGui.QWidget):\n\tdef __init__(self):\n\t\tQtGui.QWidget.__init__(self)\n\n\t\tself.qbutton=QtGui.QPushButton(self)\n\t\tself.qbutton.setText(\"Quit\")\n\t\tself.qbutton.clicked.connect(QtCore.QCoreApplication.instance().quit)\n\t\tself.qbutton.setGeometry(100,100,100,50)\n\n\t\tself.setGeometry(200,200,500,400)\n\t\tself.setWindowTitle('Quit button')\n\t\t\n #self.show()\n\n\"\"\"\"\nif __name__ == '__main__':\n \n\tapp = QtGui.QApplication(sys.argv)\n\twindow=MainWindow()\n\twindow.show()\n\n\tview = QWebView()\n\tview.setGeometry(notif_x,notif_y,notif_w,notif_h)\n\tview.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Expanding)\n\tview.setWindowFlags(QtCore.Qt.FramelessWindowHint)\n\tview.load(\"index.html\")\n\t#view.show()\n\n\tglobal_timer = QtCore.QTimer()\n\tglobal_timer.timeout.connect(lambda: scan(view))\n\tglobal_timer.start(50)\n\t\n\tsys.exit(app.exec_())\n\"\"\"","sub_path":"desktop/pygui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"45416333","text":"# Copyright 2017 AT&T Corporation.\n# All Rights Reserved.\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 mock\nimport os\n\nfrom tempest import config\nfrom tempest.tests import base\n\nfrom patrole_tempest_plugin import rbac_policy_parser\n\nCONF = config.CONF\n\n\nclass RbacPolicyTest(base.TestCase):\n\n def setUp(self):\n super(RbacPolicyTest, self).setUp()\n\n current_directory = os.path.dirname(os.path.realpath(__file__))\n self.custom_policy_file = os.path.join(current_directory,\n 'resources',\n 'custom_rbac_policy.json')\n self.admin_policy_file = os.path.join(current_directory,\n 'resources',\n 'admin_rbac_policy.json')\n self.alt_admin_policy_file = os.path.join(current_directory,\n 'resources',\n 'alt_admin_rbac_policy.json')\n self.tenant_policy_file = os.path.join(current_directory,\n 'resources',\n 'tenant_rbac_policy.json')\n\n @mock.patch.object(rbac_policy_parser, 'LOG', autospec=True)\n def test_custom_policy(self, m_log):\n default_roles = ['zero', 'one', 'two', 'three', 'four',\n 'five', 'six', 'seven', 'eight', 'nine']\n\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.custom_policy_file)\n\n expected = {\n 'policy_action_1': ['two', 'four', 'six', 'eight'],\n 'policy_action_2': ['one', 'three', 'five', 'seven', 'nine'],\n 'policy_action_3': ['zero'],\n 'policy_action_4': ['one', 'two', 'three', 'five', 'seven'],\n 'policy_action_5': ['zero', 'one', 'two', 'three', 'four', 'five',\n 'six', 'seven', 'eight', 'nine'],\n 'policy_action_6': ['eight'],\n }\n\n fake_rule = 'fake_rule'\n\n for role in default_roles:\n self.assertFalse(converter.allowed(fake_rule, role))\n m_log.debug.assert_called_once_with(\n \"{0} not found in policy file.\".format('fake_rule'))\n m_log.debug.reset_mock()\n\n for rule, role_list in expected.items():\n for role in role_list:\n self.assertTrue(converter.allowed(rule, role))\n for role in set(default_roles) - set(role_list):\n self.assertFalse(converter.allowed(rule, role))\n\n def test_admin_policy_file_with_admin_role(self):\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.admin_policy_file)\n\n role = 'admin'\n allowed_rules = [\n 'admin_rule', 'is_admin_rule', 'alt_admin_rule'\n ]\n disallowed_rules = ['non_admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n def test_admin_policy_file_with_member_role(self):\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.admin_policy_file)\n\n role = 'Member'\n allowed_rules = [\n 'non_admin_rule'\n ]\n disallowed_rules = [\n 'admin_rule', 'is_admin_rule', 'alt_admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n def test_admin_policy_file_with_context_is_admin(self):\n converter = rbac_policy_parser.RbacPolicyParser(\n None, \"test\", self.alt_admin_policy_file)\n\n role = 'fake_admin'\n allowed_rules = ['non_admin_rule']\n disallowed_rules = ['admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n role = 'super_admin'\n allowed_rules = ['admin_rule']\n disallowed_rules = ['non_admin_rule']\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertTrue(allowed)\n\n for rule in disallowed_rules:\n allowed = converter.allowed(rule, role)\n self.assertFalse(allowed)\n\n def test_tenant_policy(self):\n \"\"\"Test whether rules with format tenant_id:%(tenant_id)s work.\n\n Test whether Neutron rules that contain project_id, tenant_id, and\n network:tenant_id pass.\n \"\"\"\n test_tenant_id = mock.sentinel.tenant_id\n converter = rbac_policy_parser.RbacPolicyParser(\n test_tenant_id, \"test\", self.tenant_policy_file)\n\n # Check whether Member role can perform expected actions.\n allowed_rules = ['rule1', 'rule2', 'rule3']\n for rule in allowed_rules:\n allowed = converter.allowed(rule, 'Member')\n self.assertTrue(allowed)\n self.assertFalse(converter.allowed('admin_rule', 'Member'))\n\n # Check whether admin role can perform expected actions.\n allowed_rules.append('admin_rule')\n for rule in allowed_rules:\n allowed = converter.allowed(rule, 'admin')\n self.assertTrue(allowed)\n\n # Check whether _try_rule is called with the correct target dictionary.\n with mock.patch.object(converter, '_try_rule', autospec=True) \\\n as mock_try_rule:\n mock_try_rule.return_value = True\n\n expected_target = {\n \"project_id\": test_tenant_id,\n \"tenant_id\": test_tenant_id,\n \"network:tenant_id\": test_tenant_id\n }\n\n for rule in allowed_rules:\n allowed = converter.allowed(rule, 'Member')\n self.assertTrue(allowed)\n mock_try_rule.assert_called_once_with(\n rule, expected_target, mock.ANY, mock.ANY)\n mock_try_rule.reset_mock()\n","sub_path":"tests/test_rbac_policy_parser.py","file_name":"test_rbac_policy_parser.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"146396702","text":"import logging\nimport grpc\n\nimport python_to_rust_simple_pb2\nimport python_to_rust_simple_pb2_grpc\nfrom datetime import datetime\n\n\nREQUEST_COUNT = 10000\n\n\ndef run():\n with grpc.insecure_channel(\n \"localhost:50051\", compression=grpc.Compression.Gzip\n ) as channel:\n\n stub = python_to_rust_simple_pb2_grpc.PythonToRustSimpleServiceStub(channel)\n start = datetime.now()\n for i in range(REQUEST_COUNT):\n response = stub.increase(python_to_rust_simple_pb2.IncreaseRequest(num=i))\n assert response.num == i + 1\n print(f\"{REQUEST_COUNT} requests is completed in {datetime.now() - start}\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig()\n run()\n","sub_path":"python_to_rust_simple/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"415291515","text":"#!/usr/bin/env python3\n\n\"\"\"\nMake all the histograms\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom h5py import File\nfrom collections import defaultdict\nimport numpy as np\nimport re, json\n\ndef get_args():\n parser = ArgumentParser(description=__doc__)\n parser.add_argument('input_files', nargs='+')\n parser.add_argument('-c','--counts')\n parser.add_argument('-o','--output-name', required=True)\n return parser.parse_args()\n\ndef get_mass(jets, j1, j2):\n eta, phi, pt = [jets['jet_' + x] for x in ['eta','phi','pt']]\n m2 = 2*pt[:,j1]*pt[:,j2]*(np.cosh(eta[:,j1] - eta[:,j2]) -\n np.cos(phi[:,j1] - phi[:,j2]))\n return np.sqrt(m2)\n\nclass Histogram:\n def __init__(self, edges=0, do_errors=False):\n self.counts = 0\n self.edges = edges\n self.errors = 0\n self._do_errors = do_errors\n def fill(self, values, weights=None):\n counts, edges = np.histogramdd(\n values, bins=self.edges, weights=weights)\n self.counts += counts\n if self._do_errors:\n errors, _ = np.histogramdd(\n values, bins=self.edges, weights=weights**2)\n self.errors += errors\n def __iadd__(self, other):\n self.counts += other.counts\n self.errors += other.errors\n # todo, check the edges and do_errors\n # but also allow them to be different if the old histogram is\n # empty\n self.edges = other.edges\n self._do_errors = other._do_errors\n return self\n def __add__(self, other):\n hist = Histogram(np.array(self.edges))\n hist.counts = np.array(self.counts)\n hist.errors = np.array(self.errors)\n hist._do_errors = self._do_errors\n hist += other\n return hist\n def write_to(self, group, name):\n hist_group = group.create_group(name)\n hist_group.attrs['hist_type'] = 'n_dim'\n hist_group.create_dataset('values', data=self.counts,\n chunks=self.counts.shape)\n if self._do_errors:\n hist_group.create_dataset('errors', data=np.sqrt(self.errors),\n chunks=self.counts.shape)\n for num, edges in enumerate(self.edges):\n hist_group.create_dataset(f'axis_{num}', data=edges)\n\ndef make_hists(grp, hists, sample_norm, slice_size=1000000):\n event_ds = grp['1d']\n jets_ds = grp['2d']\n mass_binning = np.concatenate(\n ([-np.inf], np.linspace(0, 1e3, 100+1), [np.inf]))\n for start in range(0, event_ds.shape[0], slice_size):\n sl = slice(start, start+slice_size)\n weights = event_ds['weight', sl] * sample_norm\n jets = jets_ds[sl,:]\n\n pass_jvt = jets['jet_JvtPass_Medium'] == 1\n good_jets = pass_jvt & ~np.isnan(jets['jet_eta'])\n good_jet_number = np.add.accumulate(good_jets, axis=1)\n n_jets = good_jet_number[:,-1]\n good_jet_number[~good_jets] = 0\n good_events = n_jets >= 3\n\n weights = weights[good_events]\n jets = jets[good_events,:]\n good_jet_number = good_jet_number[good_events,:]\n\n sel_jets = np.stack(\n [jets[good_jet_number == x] for x in [1,2,3]], axis=1)\n\n mass23 = get_mass(sel_jets, 1, 2)\n mass13 = get_mass(sel_jets, 0, 2)\n mass12 = get_mass(sel_jets, 0, 1)\n masses = np.stack((mass12, mass13, mass23), axis=1)\n\n mass_hist = Histogram([mass_binning]*masses.shape[1])\n mass_hist.fill(masses, weights=weights)\n hists['mass'] += mass_hist\n\n mass_1323 = Histogram([mass_binning]*2, do_errors=True)\n mass_1323.fill(np.stack((mass13,mass23), axis=1), weights=weights)\n hists['mass_1323'] += mass_1323\n\n return hists\n\ndef run():\n args = get_args()\n if args.counts:\n with open(args.counts) as cfile:\n counts_dict = json.load(cfile)\n else:\n counts_dict = defaultdict(lambda: 1.0)\n hists = defaultdict(Histogram)\n id_re = re.compile('\\.([0-9]{6,8})\\.')\n for fname in args.input_files:\n sample_id = id_re.search(fname).group(1)\n sample_norm = 1 / float(counts_dict[sample_id])\n with File(fname,'r') as h5file:\n grp = h5file['outTree']\n n_events = grp['1d'].shape[0]\n print(f'running on {n_events:,} events')\n make_hists(grp, hists, sample_norm)\n\n with File(args.output_name,'w') as out_file:\n for name, hist in hists.items():\n hist.write_to(out_file, name)\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"make_hists.py","file_name":"make_hists.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"390076858","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nimport ast\n\n@frappe.whitelist()\ndef get_resource_complete(parent_table, child_tables):\n \"\"\"get table and child tables\n\n args:\n parent_table -- parent table name\n child_tables -- list of [target column name, child table name] ex: [['items', 'tabDetail']]\n \"\"\"\n child_tables = ast.literal_eval(child_tables)\n parent = frappe.db.sql(\"SELECT * FROM `%s`\" % parent_table, as_dict=True)\n parent_length = len(parent)\n for child in child_tables:\n tmp = frappe.db.sql(\"SELECT * FROM `%s` ORDER BY idx\" % child[1], as_dict=True)\n ln = len(tmp)\n for i in range(ln):\n for j in range(parent_length):\n if tmp[i][\"parent\"] == parent[j][\"name\"]:\n if child[0] not in parent[j]:\n parent[j][child[0]] = []\n parent[j][child[0]].append(tmp[i])\n break\n return parent\n\n@frappe.whitelist()\ndef get_theme_setting():\n data = frappe.db.sql(\"\"\"SELECT * FROM `tabSingles` WHERE doctype = 'Theme Setting' \"\"\", as_dict=1)\n return data\n","sub_path":"bdtheme/provider.py","file_name":"provider.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"26758941","text":"import urllib.request\nimport json\nfrom urllib.parse import quote\n\n#зоны\n\"\"\"\ngeourl = \"http://api.unit-online.ru/zones\"\nrespornse = urllib.request.urlopen(geourl)\ncontent = respornse.read()\ndata = json.loads(content.decode(\"utf8\"))\nfor i in data[\"zones\"]:\n print(i)\n\"\"\"\n#поиск персонажа\n\"\"\"\ndef poiskpers(nick):\n geourl = \"http://api.unit-online.ru/online?type=user&name={0}\".format(quote(nick))\n respornse = urllib.request.urlopen(geourl)\n i = respornse.read()\n data = json.loads(i.decode(\"utf8\"))\n print()\n\n if \"clan\" in data[\"user\"]:\n return \" %s[%s]\" \\\n \"\" \\\n \" %s \" \\\n % (data[\"user\"][\"clan\"], nick, data[\"user\"][\"level\"], data[\"user\"][\"id\"], data[\"online\"])\n elif \"clan\" not in data[\"user\"]:\n return \"%s[%s]\" \\\n \"\" \\\n \" %s \" \\\n % (nick, data[\"user\"][\"level\"], data[\"user\"][\"id\"], data[\"online\"])\n\nprint(poiskpers(\"жириновский в в\"))\n\"\"\"\n\noruzh = {\"Ближний бой\":{}, \"Энергетическое оружие\":{}, \"Тяжёлое оружие\":{}, \"Лёгкое оружие\":{}}\nbb = []\ngeourl = \"http://api.unit-online.ru/items?type={0}\".format(quote(\"оружие\"))\nrespornse = urllib.request.urlopen(geourl)\ni = respornse.read()\ndata = json.loads(i.decode(\"utf8\"))\nfor i in data[\"items\"]:\n geourl = \"http://api.unit-online.ru/item?id=%s\" % i[\"id\"]\n respornse = urllib.request.urlopen(geourl)\n ctrp = respornse.read()\n data1 = json.loads(ctrp.decode(\"utf8\"))\n print(data1[\"item\"][\"params\"])\n","sub_path":"parsejson/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"12479019","text":"import boto3\nimport json\nimport logging\n\nfrom botocore.exceptions import ClientError\n\n\nlogging.basicConfig(\n format='%(asctime)s|%(name).10s|%(levelname).5s: %(message)s',\n level=logging.WARNING\n)\n\nlog = logging.getLogger('LoggerDefinition')\nlog.setLevel(logging.DEBUG)\n\n\n\nclass LoggerDefinition(object):\n\n\n def __init__(self, s):\n\n self._gg = s.client('greengrass')\n self._iot = s.client('iot')\n\n\n def formatDefinition(self, config, cfntmp):\n ''' Format a Cloudformation Greengrass Group Logger Definition.\n '''\n loggers = []\n\n for logger in config.get('Loggers', []):\n loggers.append(logger)\n\n cfntmp.format(loggers=json.dumps(loggers))\n","sub_path":"gg_manager/definitions/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"274723376","text":"#Implementation af fixpunktsmetoden til bestemmelse af nulpunkt\nimport matplotlib.pyplot as plt\nimport math\nimport numpy as np\n\n#Funktionen for fixpunktsmetoden\ndef iter(f, xinit, N):\n L1 = [i for i in range(N+1)]\n L2 = [0.0 for i in range(N+1)]\n L2[0] = xinit\n for i in range(N):\n L2[i+1] = f(L2[i])\n return zip(L1, L2)\n\n#Den oprindelige funktion\ndef f(x):\n return x*np.cosh(75/x)-x-15\n\n#De to forskellige omskrivniger (g(x))\ndef func1(x):\n return x*np.cosh(75/x)-15 #Den konvergerer\n\ndef func2(x):\n return (x+15)/(np.cosh(75/x)) #Den konvergerer ikke\n\n#Variable\nx0=100 #Initierende gæt\niterationer=30 #Antal iterationer\n\n#Den omskrivning der undersøges\nf_valgt = func1\n\nX = iter(f_valgt,x0,iterationer)\n\nprint('Iteration Værdi')\n\nfor i, fi in X:\n print('%5d %5.8E' % (i, fi))\n\n#Herunder sættes hvad der skal plottes\nx = np.linspace(-100,1000,1000)\ny1 = f_valgt(x) #Hvilken omskrivning der printes\ny2 = x # y = x printes\ny_oprindelig = f(x) #Den oprindelige funktion, f(x), printes\n\n#Funktionerne plottes\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\n#Akserne tilpasses\nplt.axis([1, 250, 0, 250])\n\n#Plotter den valgte funktion samt y=x\nplt.plot(x, y1, 'r', label=\"g(x)\")\nplt.plot(x, y2, 'b', label='y = x')\nplt.plot(x, y_oprindelig, '--k', label='f(x)')\n\n#Modifikation af plots\nax.spines['right'].set_color('none') #Fjerner højre side af kassen\nax.spines['top'].set_color('none') #Fjerner toppen af kassen\nplt.axhline(c = 'black', lw = 0.7) #Tilføjer x-akse\nplt.legend(loc=\"best\")\nplt.show()","sub_path":"Eksamen_1/Iteration.py","file_name":"Iteration.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"558542494","text":"# python3 showflattened.py flattened_images-x10-y15.txt 15 10 0\n\"\"\" get 1d flattened image to an picture on the sreen\nsee CHANGE below\n\"\"\"\nimport numpy as np\nimport sys\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\nA = np.loadtxt(sys.argv[1])\nprint(A.shape)\nydim=int(sys.argv[2])\nxdim=int(sys.argv[3])\nB=A.reshape((A.shape[0],ydim, xdim))\n#print(B)\n\n\nbigfig= np.concatenate(B[:][:][:],1)\nprint (bigfig.shape)\n#newshapeY = int(round(bigfig.shape[0]*2))\n#newshapeX= int(round(bigfig.shape[1]/2))\n#print(newshapeY, newshapeX)\n#bigfig= bigfig.reshape((150, -1))\n\n# CHANGE (if dimensions do not match)\nif int(sys.argv[4]) > 0:\n bigfig= np.hsplit(bigfig,sys.argv[4])\n bigfig= np.concatenate(bigfig[:][:][:],0)\n\n#bigfig=np.asarray(bigfig)\n#bigfig = np.asarray(bigfig)\nprint(bigfig.shape)\nplt.imshow(bigfig, cmap = 'gray', interpolation = 'bicubic')\nplt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis\nplt.show()\n\n\n","sub_path":"showflattened.py","file_name":"showflattened.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"318058771","text":"from django import forms\nfrom django.forms import ModelForm\nfrom django.utils.translation import gettext_lazy as _\nfrom django.contrib.auth import get_user_model\n\nfrom peanut.store.models import Address, Customer, ShippingContact\n\nclass PaymentMethodForm(forms.Form):\n token_id = forms.CharField(widget=forms.HiddenInput(),\n required=False)\n name = forms.CharField(label=_('Nombre del tarjetahabiente'),\n max_length=25,\n widget=forms.TextInput(attrs={\n 'size': 25,\n 'maxlength': 25,\n 'data-conekta': 'card[name]'}))\n reference = forms.CharField(label=_('Numero de tarjeta de credito'),\n max_length=26,\n widget=forms.TextInput(attrs={\n 'size': 26,\n 'maxlength': 26,\n 'data-conekta': 'card[number]'}))\n card_cvc = forms.CharField(label='CVC',\n max_length=4, \n widget=forms.TextInput(attrs={\n 'size': 4,\n 'maxlength': 4,\n 'data-conekta': 'card[cvc]'}))\n exp_month = forms.CharField(label='Fecha de expiracion (MM/AAAA)',\n max_length=2, \n widget=forms.TextInput(attrs={\n 'size': 2,\n 'maxlength': 2,\n 'data-conekta': 'card[exp_month]'}))\n exp_year = forms.CharField(label='/',\n max_length=4, \n widget=forms.TextInput(attrs={\n 'size': 4,\n 'maxlength': 4,\n 'data-conekta': 'card[exp_year]'}))\n\nclass PaymentMethodUpdateForm(forms.Form):\n name = forms.CharField(label=_('Nombre del tarjetahabiente'),\n max_length=25,\n widget=forms.TextInput(attrs={\n 'size': 25,\n 'maxlength': 25,\n 'data-conekta': 'card[name]'}))\n exp_month = forms.CharField(label='Fecha de expiracion (MM/AAAA)',\n max_length=2, \n widget=forms.TextInput(attrs={\n 'size': 2,\n 'maxlength': 2,\n 'data-conekta': 'card[exp_month]'}))\n exp_year = forms.CharField(label='/',\n max_length=4, \n widget=forms.TextInput(attrs={\n 'size': 4,\n 'maxlength': 4,\n 'data-conekta': 'card[exp_year]'}))\n\nclass ShippingContactForm(forms.Form):\n name = forms.CharField(max_length=50)\n phone = forms.CharField(max_length=50)\n between_streets = forms.CharField(max_length=100)\n street1 = forms.CharField(max_length=100)\n street2 = forms.CharField(max_length=100)\n city = forms.CharField(max_length=50)\n state = forms.CharField(max_length=50)\n country = forms.CharField(max_length=2)\n postalcode = forms.CharField(max_length=5)\n residential = forms.BooleanField()\n\nclass AddressForm(ModelForm):\n \n class Meta:\n model = Address\n fields = '__all__'\n\nclass CustomerForm(forms.Form):\n first_name = forms.CharField(label=_('first name'), max_length=30)\n last_name = forms.CharField(label=_('last name'), max_length=30)\n phone = forms.CharField(max_length=50, required=False)\n email = forms.EmailField(label=_('email address'))","sub_path":"peanut/store/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"609978220","text":"# Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport netket as nk\nfrom scipy.sparse.linalg import eigs\n\n# 1D Lattice\ng = nk.graph.Hypercube(length=14, n_dim=1, pbc=True)\n\n# Hilbert space of spins on the graph\nhi = nk.hilbert.Spin(s=0.5, graph=g)\n\n# Ising spin hamiltonian\nha = nk.operator.Ising(h=1.0, hilbert=hi)\n\n# Use scipy sparse diagonalization\nvals, vecs = eigs(ha.to_sparse(), k=3, which=\"SR\")\nprint(\"eigenvalues with scipy sparse:\", vals.real)\n\n# Use internal Lanczos Solver Instead\n# Perform Lanczos Exact Diagonalization to get lowest three eigenvalues\nres = nk.exact.lanczos_ed(ha, first_n=3, compute_eigenvectors=True)\n\n# Print eigenvalues\nprint(\"\\neigenvalues with internal solver:\", res.eigenvalues)\n\n# Compute energy of ground state\nprint(\"\\ng.s. energy:\", res.mean(ha, 0).real)\n\n# Compute energy of first excited state\nprint(\"\\nfirst excited energy:\", res.mean(ha, 1).real)\n","sub_path":"Examples/ExactDiag/ising1d.py","file_name":"ising1d.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"127017699","text":"import json\nfrom django.conf import settings\n\nfrom scm.v1.ultilities import get_data\nfrom scm.v1.models import Projects\n\nclass ProjectsFunction:\n\n user = None\n\n def __init__(self, user):\n self.user = user\n\n def create(self, **kwargs):\n try:\n project_obj, created = Projects.objects.get_or_create(uuid=kwargs['uuid'],\n owner=self.user,\n name=kwargs['name'],\n key=kwargs['key'])\n print(project_obj)\n if project_obj and created is True:\n project_obj.description = kwargs['description']\n project_obj.is_private = kwargs['is_private']\n project_obj.created_date = kwargs['created']\n project_obj.modified_date = kwargs['updated']\n project_obj.save()\n return project_obj, True\n except Exception as ex:\n print(ex)\n return None, False\n\n\n def get_projects_from_bitbucket(self):\n try:\n url = settings.BITBUCKET_URL + '/' + settings.BITBUCKET_VER + \\\n '/teams/' + settings.BITBUCKET_TEAM + '/projects/'\n list_project = get_data(url)\n dict_project_name = {}\n if list_project is not None:\n json_project = json.loads(list_project)\n pagelen = int(json_project[\"pagelen\"])\n # size_br = int(json_branch[\"size\"])\n page_br = int(json_project[\"page\"])\n # page_next = json_branch[\"next\"]\n list_values_project = json_project[\"values\"]\n\n for project in list_values_project:\n data = {\n 'uuid': project['uuid'],\n 'repositories': project['links']['repositories']['href'],\n 'name': project[\"name\"],\n 'created': project['created_on'],\n 'updated': project['updated_on'],\n 'is_private': project['is_private'],\n 'description': project['description'],\n 'key': project[\"key\"],\n }\n project_obj, result = self.create(**data)\n if result is False:\n print(project)\n return True\n except Exception as ex:\n print(ex)\n return None\n\n\n def get(self):\n try:\n return Projects.objects.all()\n except Exception as ex:\n return None\n\n\n def get_by_key(self, key):\n try:\n return Projects.objects.get(key=key)\n except Exception as e:\n print(e)\n return None\n\n\n","sub_path":"controller/scm/v1/modules/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"94491835","text":"from __future__ import absolute_import\nfrom datetime import datetime, timedelta\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.http import HttpRequest\n\nimport logging\nfrom dimagi.utils.parsing import string_to_datetime\n\ndef wrap_with_dates():\n \"\"\"Wraps a request with dates based on url params or defaults and\n Checks date validity.\"\"\"\n # this is loosely modeled after example number 4 of decorator\n # usage here: http://www.python.org/dev/peps/pep-0318/\n def get_dates(f):\n def wrapped_func(*args, **kwargs):\n # wrap everything besides the function call in a try/except\n # block. we don't ever want this to prevent the \n # basic view functionality from working. \n # attempt to find the request object from all the argument\n # values, checking first the args and then the kwargs \n req = None\n for arg in args:\n if _is_http_request(arg):\n req = arg\n break\n if not req:\n for arg in kwargs.values():\n if _is_http_request(arg):\n req = arg\n break\n if req:\n dict = req.POST if req.method == \"POST\" else req.GET\n req.startdate = None\n req.enddate = None\n if \"startdate\" in dict:\n if \"enddate\" in dict:\n req.startdate = string_to_datetime(dict[\"startdate\"])\n req.enddate = string_to_datetime(dict[\"enddate\"])\n if req.enddate < req.startdate:\n raise Exception((\"You can't have an end date \"\n \"of %s after start date of %s\")\n % (req.enddate, req.startdate))\n else:\n # TODO: Be more graceful\n raise Exception(\"You have to specify both or 0 dates!\")\n else:\n # default to the current month\n now = datetime.now()\n first_of_next_month = datetime(now.year, now.month + 1, 1)\n req.enddate = first_of_next_month - timedelta(days=1)\n req.startdate = datetime(now.year, now.month, 1)\n \n return f(*args, **kwargs) \n if hasattr(f, \"func_name\"):\n wrapped_func.func_name = f.func_name\n return wrapped_func\n else:\n # this means it wasn't actually a view. \n return f \n return get_dates\n\ndef _is_http_request(obj):\n return obj and isinstance(obj, HttpRequest)\n\ndef _validate_timeouts(refresh_stale, cache_timeout):\n if not isinstance(cache_timeout, int):\n raise ValueError('Cache timeout should be an int. '\n 'It is the number of seconds until the cache expires.')\n if not isinstance(refresh_stale, int):\n raise ValueError('refresh_stale should be an int. '\n 'It is the number of seconds to wait until celery regenerates the cache.')\n\ndef cache_report(refresh_stale=1800, cache_timeout=3600):\n _validate_timeouts(refresh_stale, cache_timeout)\n def cacher(func):\n def retrieve_cache(report):\n # cache_overrides\n if report.request.GET.get('cache') == 'no':\n use_cache = False\n elif hasattr(settings, 'REPORT_CACHING'):\n use_cache = settings.REPORT_CACHING\n else:\n use_cache = True\n\n from corehq.apps.reports.generic import GenericReportView\n if not isinstance(report, GenericReportView):\n raise ValueError(\"The decorator 'cache_report' is only for reports that are instances of GenericReportView.\")\n\n if report._caching or use_cache is False:\n if use_cache is False:\n logging.info(\"Not using old cache for report %s.\" % report.name)\n\n context = None\n cache_key = report.generate_cache_key(func.__name__)\n\n cached_data = None\n try:\n cached_data = cache.get(cache_key)\n except Exception as e:\n logging.error(\"Could not fetch cache for report %s due to error: %s\" % (report.name, e))\n\n if isinstance(cached_data, dict) and use_cache is not False:\n data_key = report.queried_path\n context = cached_data.get(data_key)\n\n if context is None:\n context = func(report)\n\n try:\n from corehq.apps.reports.tasks import report_cacher\n report_cacher.delay(report, func.__name__, cache_key,\n current_cache=cached_data, refresh_stale=refresh_stale, cache_timeout=cache_timeout)\n except Exception as e:\n logging.error(\"Could not send <%s, %s> to report_cacher due to error: %s\" %\n (report.__class__.__name__, func.__name__, e))\n\n return context\n return retrieve_cache\n return cacher\n\ndef cache_users(refresh_stale=1800, cache_timeout=3600):\n _validate_timeouts(refresh_stale, cache_timeout)\n def cacher(func):\n def retrieve_cache(domain, **kwargs):\n if hasattr(settings, 'REPORT_CACHING'):\n use_cache = settings.REPORT_CACHING\n else:\n use_cache = True\n\n caching = kwargs.get('caching', False)\n simplified = kwargs.get('simplified', False)\n\n if caching or not simplified or use_cache is False:\n if use_cache is False:\n logging.info(\"Not caching users.\")\n return func(domain, **kwargs)\n\n individual = kwargs.get('individual')\n group = kwargs.get('group')\n user_filter = kwargs.get('user_filter')\n\n cache_key = \"%(domain)s:USERS:%(group)s:%(individual)s:%(filters)s\" % dict(\n domain=domain,\n group=group,\n individual=individual,\n filters=\".\".join([\"%s\" % f.type for f in user_filter if f.show])\n )\n\n cached_data = None\n try:\n cached_data = cache.get(cache_key)\n except Exception as e:\n logging.error('Could not fetch cached users list for domain %s due to error: %s' % (domain, e))\n\n user_list = None\n if isinstance(cached_data, dict):\n user_list = cached_data.get('data')\n\n if user_list is None:\n user_list = func(domain, **kwargs)\n\n try:\n from corehq.apps.reports.tasks import user_cacher\n user_cacher.delay(domain, cache_key, cached_data, refresh_stale, cache_timeout, caching=True, **kwargs)\n except Exception as e:\n logging.error(\"Could not send user list for domain %s to user_cacher due to error: %s\" % (domain, e))\n\n return user_list\n return retrieve_cache\n return cacher","sub_path":"corehq/apps/reports/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":7169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"575905429","text":"import pygame, sys\nfrom pygame.locals import *\n\ndef draw_grid():\n screen.fill(BLACK)\n for y in range(height, h, height):#horizontal lines\n pygame.draw.line(screen, bg, (width, y), (w - width, y), 1)\n for x in range(width, w, width):#vertical lines\n pygame.draw.line(screen, bg, (x, height), (x, h - height), 1)\n\ndef draw_player():\n pygame.draw.rect(screen, [255, 255, 55], [left, top, width, height], 0)\n\n# Mostra a tela final com a pontução obtida. Representa o placar final.\ndef mostra_pontuacao_final(screen, pokemonCount):\n sys.stdout.write(\"Capturas: \" + str(pokemonCount) + \" Pokemons \")\n\npygame.init()\nclock = pygame.time.Clock()\nw = 80\nh = 80\nleft = 20\ntop = 40\nwidth = 20\nheight = 20\nYELLOW = (255, 255, 55)\nbranco = (255, 255, 255)\nBLUE = (0, 0, 255)\nBLACK = (0, 0, 0)\nbg = (255, 255, 255)\nx = 0\ny = 0\nisFirstPokemon = True\nbulbassauro = 1\ncharmander = 1\nsquirtle = 1\npikachu = 1\npokemonCount = 0\nscreen = pygame.display.set_mode((600, 600))\ngameExit = False\nmostra_pontuacao_final(screen, pokemonCount)\n\nwhile not gameExit:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameExit = True\n if isFirstPokemon and top == 40 and left == 20:\n pokemonCount += 1\n isFirstPokemon = False\n bulbassauro -= 1\n if event.type == KEYDOWN:\n if event.key == K_DOWN and top < 40:\n print(\"Orientação: S\");\n if bulbassauro > 0 and top == 20 and left == 20: # Bulbassauro\n pokemonCount += 1\n bulbassauro -= 1\n elif charmander > 0 and top == 20 and left == 40: # charmander\n pokemonCount += 1\n charmander -= 1\n top += 20\n if event.key == K_UP and top > 20:\n print(\"Orientação: N\");\n if squirtle > 0 and top == 40 and left == 40: # squirtle\n pokemonCount += 1\n squirtle -= 1\n elif pikachu > 0 and top == 40 and left == 20: # pikachu\n pokemonCount += 1\n pikachu -= 1\n top -= 20\n if event.key == K_RIGHT and left < 40:\n print(\"Orientação: E\");\n if charmander > 0 and top == 40 and left == 20: # charmander\n pokemonCount += 1\n charmander -= 1\n elif squirtle > 0 and top == 20 and left == 20: # squirtle\n pokemonCount += 1\n squirtle -= 1\n left += 20\n if event.key == K_LEFT and left > 20:\n print(\"Orientação: O\");\n if bulbassauro > 0 and top == 40 and left == 40: # Bulbassauro\n pokemonCount += 1\n bulbassauro -= 1\n elif pikachu > 0 and top == 20 and left == 40: # pikachu\n pokemonCount += 1\n pikachu -= 1\n left -= 20\n mostra_pontuacao_final(screen, pokemonCount)\n\n\n draw_grid()\n draw_player()\n pygame.display.flip()\n\npygame.quit()\n","sub_path":"desafio.py","file_name":"desafio.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"234824984","text":"from django.urls import include, path\nfrom .import views\napp_name = \"authentication\"\nurlpatterns = [\n path('', views.home, name='home'),\n path('index/', views.index, name='index'),\n path('register/',views.register,name='register'),\n path('login/',views.login_,name='login'),\n path('logout/',views.logout_,name='logout'),\n path('activate///',views.activate, name='activate'),\n]","sub_path":"authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"489258783","text":"from django.conf.urls import include, url\r\nfrom django.contrib import admin\r\nfrom views import *\r\n\r\nurlpatterns = [\r\n url(r'1', swift),\r\n url(r'^put_container/$', put_container),\r\n url(r'^delete_container/$', delete_container),\r\n url(r'^delete_object/$', delete_object),\r\n url(r'^put_object/$', put_object),\r\n url(r'^get_object/$', get_object),\r\n url(r'^put_objectfile/$', put_objectfile),\r\n url(r'^login/$', login),\r\n url(r'^loin/$', loin),\r\n\r\n]","sub_path":"cloud/swiftapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"279252968","text":"from django.utils import timezone\nfrom django.conf import settings\n\nfrom .. import ActionTest\n\nimport pytz\nfrom datetime import timedelta\n\nclass ViewAccount(ActionTest):\n def setUp(self):\n super(ViewAccount, self).setUp()\n self.data = {\n u'Sequence': 2,\n u'Mobile': u'233542751610',\n u'SessionId': u'aeb67d5e6e6b48409ad19a43eaa62b91',\n u'ServiceCode': u'711*78',\n u'Operator': u'MTN',\n u'Message': u'4',\n u'Type': u'Response',\n u'first_name': u'Ola',\n u'last_name': u'Olu',\n u'is_agent': u'True',\n }\n self._set_session_menu_option(4)\n\n # Create check-ins\n self.p1 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b84'),\n self.agent, 'AW13916', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 4, 59, 10)), number_of_slots=2)\n self.p2 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b85'),\n self.agent, 'AW13917', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 5, 5, 10)), number_of_slots=1)\n self.p3 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b86'),\n self.agent, 'AW13918', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 5, 12, 10)), number_of_slots=1)\n self.p4 = self._create_parking(self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b87'),\n self.agent, 'AW13919', pytz.timezone('UTC').localize(timezone.datetime(2017, 1, 1, 5, 18, 10)), number_of_slots=1)\n\n # Check out\n hours = 4\n\n cs = self._create_session(session_id='tyb67d5e6e6b48409ad19a43eaa62b94')\n cs.succeeded = True\n cs.save()\n\n self.p1.checkout_session = cs\n self.p1.checkout_agent = self.agent\n self.p1.checkout_time = self.p1.checkin_time + timedelta(hours=hours)\n self.p1.hours = self.p1.number_of_slots * hours\n self.p1.charge = self.p1.hours * settings.CHARGE_PER_HOUR\n self.p1.save()\n\n # Create supervisor session\n self.session = self._create_session(\n session_id='aeb67d5e6e6b48409ad19a43eaa62b99', phone_number='0542751615',\n actor_first_name='Titi', actor_last_name='Lope'\n )\n self._set_session_menu_option(4, session_id='aeb67d5e6e6b48409ad19a43eaa62b99')\n\n # Create supervisor\n self.supervisor = self._create_agent('Titi', 'Lope', zone=self.zone)\n\n def tearDown(self):\n self.p1.delete()\n self.p2.delete()\n self.p3.delete()\n self.p4.delete()\n self.session.delete()\n self.supervisor.delete()","sub_path":"core/tests/views/4_view_account/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"266826142","text":"listing = [\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"ELEVATOR\",\n \"INTERCOM\",\n \"BALCONY\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"AP14630\",\n \"usableAreas\": [\n 104\n ],\n \"description\": \"Apartamento com 3 dormitórios em Cerqueira César, planta funcional e pé direito alto são alguns dos atrativos deste imóvel. São 2 dormitórios ( podendo reverter 1) sendo 1 suíte com varanda frente a Oscar freire e closet espaçoso , área de serviço e dependência completa de empregada. Apartamento todo reformado com material de primeira linha , na suíte master mármore de carrara. Excelente endereço, próximo ao Hospital das Clínicas, Incor e Emílio Ribas. Toda infraestrutura que cerca a região da Oscar Freire ( Metro, padarias, supermercados, colégios e ainda com a vantagem de fazer tudo a pé. Venha conhecer pessoalmente. -\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento com 3 dormitórios em Cerqueira César. Condomínio seguro e próximo ao metro Oscar Frei\",\n \"createdAt\": \"2018-08-03T23:42:07.220Z\",\n \"publisherId\": 82425,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"10790\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1142103609\",\n \"11928982000\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1039360272\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-19T18:40:36.992Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Cerqueira César\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"01426000\",\n \"locationId\": \"BR>Sao Paulo>NULLCentro>Cerqueira Cesar\",\n \"zone\": \"Centro\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"AP14630\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [\n 167\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"286\",\n \"price\": \"900000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/29a845a6f1cf450c238a7ced0b9d00dd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/21e945e489a5c2acd69f2e1727dfbdad.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/987109372827048c236470daa2b1f8dd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4bc0aff90081f0024ad829693e79b321.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ab235a2513273aac96423524d57fcbdf.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a03f06c05bec20a1e3d8f9543aa34739.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/16b28b8d2d2ad5ed94ddd4c985aaec85.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5ed3c5a71e29ccc9fe3cc12fd839c587.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0d57f4976d5b15e139f4a35e33aaa85a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e9b8782ffe8107854c9a79f6e8cd5aa7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e18a05e205d2f4aecd24a660682fcda3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ee1d723eb87e3c7679d31af27193ee0e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5818690c78b3c60b9042e005cda20cd3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7ab9a247a408d2648e3962f72b13e94f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/29f98ba5504023b579968da6231dc629.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/eeb2bbce42154f43537b21562d8c813f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5d75cdda2617ec129c32198e3eede1c2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/13b568b27c3878081e7a791c9d50c6c4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/783f5e5e82f5ad84d9d3c2215b18176f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f320466eb228e673ee6675c48ea59e23.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4d24008878ae92c606eb21001f291024.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/243ce4aeececf47e0d3e387de02f34f7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/25dfa42146293cd3c485f292dd3b7193.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/53f8d5bdafd44fc3a634b1658e7c0bd9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9388cec49c89d0c4cb9a4f327d4dfa4e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b2c37ddb05219a6240e0fb5aef62a117.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c4c770d46d912090f5b556fec75745ab.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"82425\",\n \"name\": \"RE/MAX URBAN IMOVEIS\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01427-000\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"1725\",\n \"zone\": \"\",\n \"street\": \"Rua Estados Unidos\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Jardim América\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11928982000\",\n \"alternative\": \"\",\n \"primary\": \"1142103609\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3a3d07db80e7863be5f9a59ada3a850d.jpg\",\n \"licenseNumber\": \"32734-J-SP\",\n \"websiteUrl\": \"http://www.remaxunion.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T22:26:33Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1039360272\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 104m²\",\n \"href\": \"/imovel/apartamento-3-quartos-cerqueira-cesar-centro-sao-paulo-com-garagem-104m2-venda-RS900000-id-1039360272/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/82425/re-max-urban-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [],\n \"feedsId\": \"23\",\n \"usableAreas\": [\n 104\n ],\n \"description\": \"Apartamento de 104 m². Sala para 2 ambientes, varanda, 3 dormitórios (1 suíte), cozinha americana, 3 banheiros, área de serviço, ar condicionado instalado, dependência de empregada, entrada de serviço independente e esquadrias com redução de ruído. O imóvel possui 1 vaga de garagem. O condomínio disponibiliza porteiro em tempo parcial e portaria remota. Localizado numa região com diversos supermercados, restaurantes e serviços. Tem como opções de lazer próximas a Praça Benedito Calixto (1,1 km), o Cine Belas Artes (1,4 km), o Conjunto Nacional (1,6 km) e o Shopping Center 3 (1,7 km). Está próximo às grandes avenidas Rebouças (200 m) e Doutor Arnaldo (800 m), o que permite fácil acesso à estação de metrô Oscar Freire e a inúmeras a linhas de ônibus.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento de 3 dormitórios na Oscar Freire\",\n \"createdAt\": \"2019-05-10T02:20:45.187Z\",\n \"publisherId\": 494334,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"41598\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1155550175\",\n \"1155550175\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"2444101798\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-20T13:46:01.765Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"PREMIUM\",\n \"externalId\": \"23\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"3140\",\n \"price\": \"1000000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"494334\",\n \"name\": \"Imóvel.aí\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01310-933\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"2444\",\n \"zone\": \"\",\n \"street\": \"Avenida Paulista\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Bela Vista\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"1155550175\",\n \"alternative\": \"\",\n \"primary\": \"1155550175\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/854fd0c248b944cbd6af65c9b382194e.jpg\",\n \"licenseNumber\": \"33226-J-SP\",\n \"websiteUrl\": \"\",\n \"leadEmails\": [],\n \"createdDate\": \"2019-01-14T11:54:45Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"2444101798\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 104m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-104m2-venda-RS1000000-id-2444101798/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/494334/imovel-ai/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"BALCONY\",\n \"GARAGE\",\n \"KITCHEN\",\n \"HEATING\",\n \"PLAYGROUND\",\n \"GOURMET_BALCONY\",\n \"GREEN_SPACE\"\n ],\n \"feedsId\": \"km196\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apto muito amplo, 3 minutos do Metrô Oscar Freire (200 m), pertinho do corredor de ônibus da Rebouças e ao lado do comércio da rua mais charmosa de São Paulo. Pertinho do Hospital das Clínicas, dos melhores restaurantes, bares, supermercados. Salão 2 ambientes amplos com ampla cozinha integrada, 3 quartos com armários embutidos sendo 1 suíte com sacada e closet + escritório, lavabo, banheiro social com blindex, área de serviço + dependência de empregada . 1 Vaga de Garagem. - Características: Ar Condicionado, Área de Serviço, Móveis Planejados, Aquecimento Central Individual, Dependncia de Empregada, Varanda, - No Condomínio: Jardins, Portaria 24h, - Proximidades: Bares e Restaurantes, Escola, Farmácia, Shopping Center, Supermercado, Bancos, Centros M��dicos, Hospitais, Lojas, Metrô, Padaria, Parque ou praça, Universidade,\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento para Venda em São Paulo, Pinheiros, 3 dormitórios, 1 suíte, 3 banheiros, 1 vaga\",\n \"createdAt\": \"2019-05-28T15:55:35.629Z\",\n \"publisherId\": 118942,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"17754\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"11940127505\",\n \"11949812349\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"2446243258\",\n \"parkingSpaces\": [\n 1\n ],\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"km196\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"0\",\n \"price\": \"1020000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1460\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a046f651a665c96de94efd71c8e2c8e0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f30cd08a601a5f51cc75ef7693e3f620.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0b115ffdfc489e45419ef3fa5ebb940c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7bf7fc238e0b267edae94b0bb6a75a93.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b34a234aacc3c59c4a949a56eacb63e2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3f90cf710d9e12d98db185acc281fcf5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/73e735a0976f2d3a2b1acdbde083d6b3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a2936d0bb5fc2e9d4c4232d7b9907a52.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9fec9f3ad5291c65c5fbb89271e3a7ea.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/54714c57b60c90b084642b24972fdd92.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/02b547e8da7fb5d28811eda6fa9f4364.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/579ea4527c3f79e07f73dd554c50f3ca.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ab37ceffd3c73eeb58c82d917e4c554f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1bf4d11d8dd9149ba1cedd95c8d32719.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cfb157460c908b67a3f26bda67a27a4a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/729aa0084c6473e6094abbca34fc0eb8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8ea8cf1eea6e150aa84547051f5a48f3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fc16a5e1fac59db893bbb250a44877ae.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8e68c1657aa3bdb712c5d57e9e3e93ec.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/99898a13a601437e8e8c33bd9539fa63.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/09d99dc05b1746a095892e1f9dfc4ab6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0fb2ba420ce424ba4e6ed4e0504f8758.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/772b7dcd18005731c877053147795a7d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9cc3e8c7bd4d7de1f9f9fdf44ca4c512.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0dce216ba195739952e2f12b1f565020.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/67708dc6d0b49a1d6eca9095a288dc68.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e901b96ff91d78b515d3a06edb828772.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/55efb006ecdead2954d24ad1d758ec56.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"118942\",\n \"name\": \"KATIA MANCEBO AVILA DE REZENDE\",\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11949812349\",\n \"alternative\": \"\",\n \"primary\": \"11940127505\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/30b925098345d433e770c48f0ec08cb9.jpg\",\n \"licenseNumber\": \"155998-F-SP\",\n \"websiteUrl\": \"http://katiamancebo.com.br/\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T18:49:36Z\",\n \"showAddress\": False\n },\n \"url\": {\n \"id\": \"2446243258\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1020000-id-2446243258/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/118942/katia-mancebo-avila-de-rezende/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"ELEVATOR\",\n \"INTERCOM\",\n \"CABLE_TV\",\n \"SECURITY_24_HOURS\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"AP0886\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento em bom estado de conservação, localizado em rua muito procurada , metragem diferenciada com planta bem distribuída , ao lado dos Jardins, poucos minutos a pé da estação Oscar Freire do METRO e próximo a todas as facilidades do bairro,Pronto para morar. -\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento residencial à venda, Pinheiros, São Paulo.\",\n \"createdAt\": \"2018-06-19T05:08:38.837Z\",\n \"publisherId\": 96828,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"19565\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1130313184\",\n \"11997143339\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1037912351\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-03T02:23:11.134Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409011\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558913,\n \"lon\": -46.673112\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"AP0886\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"270\",\n \"price\": \"1020000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/db14d72d126b7f598b5ee61dc15a19f2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/55e7f34ca042f2674ccd52217df7f861.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d94e880eb4dedfeca91c26294dda6bec.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/871763a0f8263284958d6ad7bd975dc7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/98cc97fdecfa27e1620c636533da3d91.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4f3b0c01f46ce9a44885a1dfb1744a00.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/467fca06b5775d19fbac8318f2530fc6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/41c68d582a6a1b18dd6e0621f4ff5bcc.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e6c87d0907c24bd6d106144898f130d1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/589c3b3872ef700417ac9f0187ae9d29.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/27743f267fdcbb5a4d9ba66c9248b3b4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9e072a3066cff081b1323023e62f6f30.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b0e35519a470e38e804b9d169c616d2c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cd92a4e8eda8876fe6a2e4573dd9c43f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/82e49fae352970c1a540d0697ee1cfd7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e66a81df410cc83d89aa0e1cdb37c3f0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e3d70fa4f631df6ca49e116f4561e19d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c3d855e5a656e4db1915e432dd69f1c2.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"96828\",\n \"name\": \"Simons Imóveis\",\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11997143339\",\n \"alternative\": \"\",\n \"primary\": \"1130313184\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d1770efa6cc8981e08ffb767d9a3057b.jpg\",\n \"licenseNumber\": \"61905-F-SP\",\n \"websiteUrl\": \"\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-29T17:40:52Z\",\n \"showAddress\": False\n },\n \"url\": {\n \"id\": \"1037912351\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1020000-id-1037912351/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/96828/simons-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"ELEVATOR\",\n \"INTERCOM\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"AP0600\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento perto da Estação Oscar Freire da Linha Amarela (4) do Metrô, com 3 dormitórios mais closet, sendo uma suíte, 2 banheiros, cozinha, sala de estar e área de serviço, com 1 vaga de garagem. -\",\n \"listingType\": \"USED\",\n \"title\": \"Apto à venda com 3 dormitórios (1 suíte) , 125 m² por R$ 1.028.000,00 - perto Metro Oscar Freire, P\",\n \"createdAt\": \"2019-05-30T02:15:57.394Z\",\n \"publisherId\": 227418,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"23119\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1125323747\",\n \"11941343747\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"2446522291\",\n \"parkingSpaces\": [\n 1\n ],\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"AP0600\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"3200\",\n \"price\": \"1028000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/41bb7b0fe7033ec32e1435c4664d4bf0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3f9b8f9e6b02a72a5fc13c61c66a3720.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0a9ac30e23d4bc5f36f7c59f37616a59.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/953b50d4a3815ac98d5d3d4fa774725b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f21fb59cbf049da37a18d2c922dd9381.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fa714a0751a75c7c5a6ea35156562a8a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/90f69a3c17c769383556306a78dc06c9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d0ab1cd361c3d9338acbb5a14db420ac.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ecdbf4d7f0833b4b66c809567f197aad.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6f0c4d7b86ada68e3778c238e958af68.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7b8c2acc0cd6adbb8a7f75f58a7fac9f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c143a179d6a9182f02b981421a1a8c57.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/677058ca7a5d15917a467914786153b8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/71d8ff1b5e3e4ee6dc152ae1b74af2af.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"227418\",\n \"name\": \"MAIS PADRAO INTERMEDIACOES IMOBILIARIAS LTDA.\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"05372-040\",\n \"city\": \"SAO PAULO\",\n \"streetNumber\": \"322\",\n \"zone\": \"\",\n \"street\": \"JOSE FELIPE DA SILVA\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SAO PAULO\",\n \"neighborhood\": \"JD ESTER\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11941343747\",\n \"alternative\": \"\",\n \"primary\": \"1125323747\"\n },\n \"logoUrl\": \"\",\n \"licenseNumber\": \"031350-J-SP\",\n \"websiteUrl\": \"http://www.maispadraoimoveis.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T18:23:44Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"2446522291\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1028000-id-2446522291/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/227418/mais-padrao-intermediacoes-imobiliarias-ltda/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"AIR_CONDITIONING\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"SH34724\",\n \"usableAreas\": [\n 105\n ],\n \"description\": \"Apartamento à venda em Pinheiros com áreas amplas, planta funcional e pé direito alto são alguns dos atrativos deste imóvel. Cozinha com armários planejados integrada à sala permite convívio familiar; além disso, são 3 dormitórios sendo 1 suíte com varanda e ar condicionado, closet espaçoso, área de serviço e dependência completa de empregada. Excelente endereço, próximo ao Hospital das Clínicas, a estação de metrô e à mais famosa área comercial da cidade onde encontra as suas grifes favoritas.\",\n \"listingType\": \"USED\",\n \"title\": \"Conforto em uma das ruas mais conhecidas do bairro\",\n \"createdAt\": \"2018-09-12T01:25:07.715Z\",\n \"publisherId\": 69027,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"11319\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1143692406\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1041038046\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-05-21T05:10:44.259Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"SH34724\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"deliveredAt\": \"1996-02-24T06:19:28.843Z\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"260\",\n \"price\": \"1040000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f687e3fa96d076ebd510ddd8b024a563.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5d245996e02804a0123db17c4de85db0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f9f63bda62b541a668a5f0d0780ce389.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bfff39ed08860f8003e8081c965b7802.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2e23a4158d1b12312d06dc2841278309.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8c5d77d943389147fdc225607f48ea55.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c2c6f1704f29011e292ba6186e5fb61b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cf20fe93d03e5b284fb87ad1e005048c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f9c39496f501163a0e38b8be2393475e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d143b5ea206207b94f3732ed267cc938.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7483d7c0c09a389c0edcb6d0755ab678.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bec6c29562049d8d85bff585a72e5e3b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/150bd10125e6c7506c714e70a8f6557e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/11d31ac2de2ba6e43a6023bd575ecf57.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/560f624e1449bee10b615f689447a252.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"69027\",\n \"name\": \"Sh Prime Imóveis\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"05019-010\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"794\",\n \"zone\": \"\",\n \"street\": \"Avenida Professor Alfonso Bovero\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Perdizes\"\n },\n \"phone\": {\n \"leadsPhone\": \"1143692406\",\n \"mobile\": None,\n \"alternative\": \"\",\n \"primary\": \"1143692406\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1992bd1b8345b300735cffeacfd90459.jpg\",\n \"licenseNumber\": \"25618-J-SP\",\n \"websiteUrl\": \"http://www.shprime.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T17:00:22Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1041038046\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 105m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-105m2-venda-RS1040000-id-1041038046/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/69027/sh-prime-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"PARTY_HALL\",\n \"SECURITY_24_HOURS\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"143840\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Living para 2 ambientes com lavabo, banheiro social reformado, 1 ampla suíte com varanda e closet + 2 dormitórios com armários, cozinha integrada toda planejada e repleta de armários, área de serviço, quarto de empregada. Em ótimo estado, espaçoso. Próximo ao Metrô Oscar Freire.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento espaçoso reformado com 125m² de área útil. Próximo ao Metrô Oscar Freire\",\n \"createdAt\": \"2018-08-10T19:06:21.521Z\",\n \"publisherId\": 58736,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"75\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1130812251\",\n \"11998988044\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1039603986\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-08T02:26:52.483Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"143840\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"260\",\n \"price\": \"1050000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a9d0b38427f611808fd58ef814ae6590.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b71334bc78bf00adf14dbd388b5035b9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3652b9771cfa10a9c29bce478802aa2d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5a5d2954d9d0599e30e124fd219023e2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/114c8f3f781ec931e387bec7df1f37b6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ae09f1233a406b4e06648cc597c67f39.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/39d52c1f0229fa06039bf12ad55af821.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bfbe06bb06a72b6ae590795a00b56712.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/37aca7efaf401b25c037cb6a7b6a319d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5c0c95e96204a471558918b47655bbf8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9fdda00f8eee9e7c37ec4258b93972ff.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f39dd2de77d37f69d2b440a799d76ac3.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/19f47e4131b17218ff2a740d4aa03cd5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0d71c3218ead7545b5075140b6d1e724.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/973f2a15445df995065fbd208982f690.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/00614a69bf8b6bbedd43e789fde0c894.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/54d0551efd34b66b320022c6ece7e7ab.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c4760c6326bc115527f749b06a1cbefd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fb535c66062e32348449fec7dd76042a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/eb92ecd7931fc57f30c594d670ed8d58.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0ac8f482aca92a6aa3aea3347ca78b7e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/39814664a62ade3238694cdc348b2a7b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e38864b655b5203bd4c399331de5a3f4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/07eb83a48e3ceba9a6a6189a42083733.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1078bf12a696b74d262f203a1b66dc37.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fd7b5d40f65673859b139693c818636e.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"58736\",\n \"name\": \"A2 Jardins Negocios Imobiliários LTDA\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"05409-010\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"49\",\n \"zone\": \"\",\n \"street\": \"Rua Oscar Freire\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Pinheiros\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11998988044\",\n \"alternative\": \"\",\n \"primary\": \"1130812251\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2b9968eb59dfcfbdfc447a9fbea86130.jpg\",\n \"licenseNumber\": \"19948-J-SP\",\n \"websiteUrl\": \"http://www.a2jardins.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T22:38:43Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1039603986\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1050000-id-1039603986/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/58736/a2-jardins-negocios-imobiliarios-ltda/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"NEAR_SCHOOL\",\n \"PARTY_HALL\",\n \"SECURITY_24_HOURS\",\n \"BALCONY\",\n \"NEAR_ACCESS_ROADS\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"BR658\",\n \"usableAreas\": [\n 105\n ],\n \"description\": \"Excelente Apartamento em Pinheiros totalmente reformado. Amplo, com tres dormitórios sendo uma suíte com armários, sala para dois ambientes. Cozinha americana moderna. Apartamento aconchegante. Região nobre, rua com comércios de Grifes, restaurantes de diferentes culinárias. Localização espetacular.\",\n \"listingType\": \"USED\",\n \"title\": \"Lindo Apartamento em Pinheiros!\",\n \"createdAt\": \"2018-05-27T18:03:17.552Z\",\n \"publisherId\": 227935,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"6911\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"11961936337\",\n \"11999469687\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1037278828\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-05-25T09:02:10.236Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"BR658\",\n \"bathrooms\": [\n 3\n ],\n \"totalAreas\": [],\n \"logoUrl\": \"\",\n \"deliveredAt\": \"1996-02-24T04:02:23.414Z\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"2600\",\n \"price\": \"1050000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0e99159ea96e79a20f4c954c6fb86149.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e7aae2872e8a46d8627deeab48a97731.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/774c1e4c0615b4bde985c84d5e1f94bb.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5a86e6034b857277092ba1903e22fea7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ad5877f5f1990f1298f25aaa291b01eb.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/396c4f8b17175ab3c25cb850b9c95e16.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bb4f1783d6a3048fb4ee5ea05fdcd1f5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e50d4f766e210610e6559e37caa4c04c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6c18aacb49748f2cc7c1a7205c036f94.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/b17384529a091af184074841e0778def.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d6d9b86851f71a8bfe4e9cddeca17a56.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/16bb384c42a5466636b0828ab0d66269.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e075bfc7491963be39d6ad41e7ef657b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/12d962dd04310bf3326a27883fbe1a64.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/99061dead6eaeeb3bd26d357a11be402.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/edb2e3f6328eb3d5c2e340d08e16f0d2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6da3a62d665223ab98aeed875bed54ae.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6edad5104738142b3d396fc8f2f62e74.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/83c1866e995583d695a39115d80c7359.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1350730485b7150f3b7075b5fef52976.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0782d2d312c42a8ded805e119b1382f6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c11f36307a122a1093bbce2c5bdeb83b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a8159ed1f7924affe5416001525f03a0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/23f370d0334565df12f5633d47151a43.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"227935\",\n \"name\": \"ELIZA BR7 IMÓVEIS\",\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11999469687\",\n \"alternative\": \"\",\n \"primary\": \"11961936337\"\n },\n \"logoUrl\": \"\",\n \"licenseNumber\": \"\",\n \"websiteUrl\": \"http://www.br7imoveis.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T23:16:59Z\",\n \"showAddress\": False\n },\n \"url\": {\n \"id\": \"1037278828\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 105m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-105m2-venda-RS1050000-id-1037278828/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/227935/eliza-br7-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"WATCHMAN\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"44984\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento Próximo ao Metrô Oscar Freire - REF. 44984 Apto muito amplo, sala para 2 ambientes, cozinha, 3 quartos sendo 1 suíte e com Closet, área de serviço, lavabo, cozinha, 01 vaga de garagem. Próximo ao metrô Oscar Freire (200 m), pertinho do corredor de ônibus da Rebouças e ao lado do comércio da rua mais charmosa de São Paulo. Pertinho do Hospital das Clínicas, dos melhores restaurantes, bares, supermercados.\",\n \"listingType\": \"USED\",\n \"title\": \"SAO PAULO - Padrão - PINHEIROS\",\n \"createdAt\": \"2018-10-19T06:10:14.860Z\",\n \"publisherId\": 35775,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"8139\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1131056300\",\n \"1131056300\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1042511632\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-08T01:13:36.425Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"44984\",\n \"bathrooms\": [\n 1\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"2650\",\n \"price\": \"1050000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1450\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"NEIGHBORHOOD\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/10937cb2ea7e2b1ac525917a5ba4362a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6efdf9b1f0863da0da6a3bc87cc1547e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/377ab75269b96b5ef8a2fe52c7b08856.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/81f49f783c1fab45d8e2566348f87f82.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9ec0d2798f928a59a4f0b6b03d49987c.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/762ee48c059812ccd89f2c1a9ecc26d4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5801c83eecac98ad0de864fd437ac837.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/14d7d79a9d67b9a8b05529fc398a6c3d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c0ea30159378ae688f786d9a6cca39d5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5e16e25d5d564de0a1db45c75ea87c35.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9f9131ab1b585304a96b60cd0a16c65f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c8c669e196a3da7af7f11df7c149e110.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/9b8769f4cd4c01ac7caf2607465af863.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/38d5d2c77549792693805181824c2aa1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/16ff5488b0133a5713f31e298f2266f0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4a3de9aad7b65ac102e1f721e0e5c71b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/666d3bb1638727b74a0d08004ea26781.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7c532f5d74c0e0adb94e35be7a0260d8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/7b289dd63abf8f2472ea5b91373830f0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d5bb411998003850882e4673e63d34f4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8a62ec726cdbb44d1f243aa3bfee599b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fa394c9a70e9489761ec758cfa5a878d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ed4a1cd294ec4ba25c07ea8bda312a66.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/be1324fe2054777399927834b8be3671.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1513ca6c7bbd042f36112db67f6a18ac.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/62f6f53eb676227559000e604183bef9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2295350e922b99ab847dc26a6d42571e.jpg\"\n ],\n \"videos\": [\n \"https://www.youtube.com/watch?v=ZxzdCDZqroQ\"\n ]\n },\n \"publisher\": {\n \"id\": \"35775\",\n \"name\": \"M. Lara Negocios Imobiliarios Ltda.\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01002-001\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"185\",\n \"zone\": \"\",\n \"street\": \"Rua Álvares Penteado\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Centro\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"1131056300\",\n \"alternative\": \"\",\n \"primary\": \"1131056300\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e1f634ed8c9b97de0b51bd314ec41e47.jpg\",\n \"licenseNumber\": \"20816-J-SP\",\n \"websiteUrl\": \"http://www.marcelolara.com.br/\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T20:48:40Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1042511632\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1050000-id-1042511632/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/35775/m-lara-negocios-imobiliarios-ltda/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"KITCHEN\",\n \"INTERCOM\",\n \"POOL\",\n \"PLAYGROUND\",\n \"PARTY_HALL\",\n \"GARDEN\"\n ],\n \"feedsId\": \"KA4551\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"Apartamento 185 m² , 03 dormitórios,sendo 01 suíte, living para 02 ambientes,lavabo,areá de serviço e 01 vaga de garagem. Será um prazer encontrar o seu imóvel! Todas as informações publicadas neste anúncio, incluindo preço, metragem do imóvel e valores são aproximadas e não garantidas, devendo ser confirmadas conforme o interesse do cliente. Somos uma imobiliária dinâmica que conta com a experiência de profissionais sedimentados no mercado há mais de 15 anos. Nosso foco está sempre direcionado ao cliente e nos resultados a serem alcançados, atuando com ética e responsabilidade.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento a venda\",\n \"createdAt\": \"2018-09-28T07:31:54.913Z\",\n \"publisherId\": 97354,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"16476\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1145631800\",\n \"11938081800\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1041737287\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-05-15T23:01:11.260Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"KA4551\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 150\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"286\",\n \"price\": \"1060000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bbee539bb1ce08980aa5e8849d8fd39b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/788428bc30c203edfcde9efafd94917e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/62c6d37f5f6f599d20b5ebd98d1e8952.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/cb56e1a241970c9ac34b50cc75c96674.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/332f15699b1232889e6d07a31a0b84de.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a97ec2ef053b554780c846cde587d016.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/052fb6dfe4f87a21822f5f16e543bbee.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2f10e0c9d4e2e8bb23b65598d53cf7d6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6cef8261f0f67560d8d0f2739ae7acf9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2bd21765cf2c3a5715086818379815f8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c2ce5165a1015ddc9db63bd3748856ac.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/eb556e5f71684ad1ec1fe5915568b557.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c5979a536d7e408099157714497991a9.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/fb87c5d4fa917777773d2cf7cbdd109a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6eacce88253a2deeca524b957ba56ee2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/98d9c343aabfb519d7a44358ada8e7f1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/46467dcee4dfb5a810eb3e2f035c273f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e3a09078dd313b39836257c5c3f34eca.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4ba42d37ee7396ad07a45a339f0bd7f2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/3bb06aeef813ec815e217abde5172f26.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/448a9c1251a2d926130378dd4d40d540.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1f7a0551827b7e1f0348e01051e81b43.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/be9ca3ad17e6c1d795702ff3f03a2a59.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0f379672a9623234a6ec40e748040821.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d62dc7030c29b0c60090f5d81e4b1175.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"97354\",\n \"name\": \"KASACOR IMOVEIS\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01240-001\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"1380\",\n \"zone\": \"\",\n \"street\": \"Av. Angelica\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Higienópolis\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11938081800\",\n \"alternative\": \"\",\n \"primary\": \"1145631800\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6c789e5c88aaf6bc12f717f2357e0039.jpg\",\n \"licenseNumber\": \"27037-J-SP\",\n \"websiteUrl\": \"http://www.kasacorimoveis.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T17:54:48Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1041737287\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1060000-id-1041737287/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/97354/kasacor-imoveis/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [\n \"ELEVATOR\",\n \"GARDEN\",\n \"PARTY_HALL\",\n \"PLAYGROUND\",\n \"POOL\",\n \"BALCONY\",\n \"NEAR_ACCESS_ROADS\",\n \"NEAR_SHOPPING_CENTER\",\n \"GATED_COMMUNITY\",\n \"INTERCOM\",\n \"SECURITY_24_HOURS\",\n \"KITCHEN\",\n \"SERVICE_AREA\"\n ],\n \"feedsId\": \"\",\n \"usableAreas\": [\n 125\n ],\n \"description\": \"O apartamento de 125 metros Apartamento para a venda 125 m² é de frente, sendo 3 quartos com 1 suite, cozinha balcão, lavabo, 1 vaga com armários e piso de madeira. Áreas comuns: - Jardim - Piscina - Playground - Salão de festas Localização: - Próximo a Fundação Faculdade de Medicina - Próximo ao Hospital Jardins - Próximo a Estação Pinheiros de metro\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento para venda com 125 metros quadrados e 3 quartos em Pinheiros - São Paulo - SP.\",\n \"createdAt\": \"2018-09-22T23:56:03.195Z\",\n \"publisherId\": 136127,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"VIVAREAL\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"11981182245\",\n \"11981182245\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1041554133\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-03-28T21:05:29.122Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"streetNumber\": \"1513\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"0408\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 125\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"285\",\n \"price\": \"1100000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"ALL\",\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0732967f53018eb04e9f18f8216e883f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/378fba8984029f488e5e7fcedc3f7fcf.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d0fa2fba76b8aecd7bdf8130edb4d5fa.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/c185e1c02c6d37bc2bdd5665868b4afc.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4555576c2980dbd8f5d15cfe2f3c1177.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/463943481565baeefc28b5fb124726d7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0dcacb01c7b8a4cbec39e92ff26fde3a.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/649550dd6e0d98953165720cc77e7c1e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e88851a7cd2f2cf406bb81d857574bb5.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/e846960fae743c995519fcf1cd3c71e8.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2772d2e61088ca3ac99dd682bbd28421.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/f5a933a036cf168a412003d08ef907bf.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/25cf82b9971d994487e92d0f0f3da875.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/0dbf72f9dc53055f048d56e246a80161.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2ba123e84f6df359d0b54926eabea117.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d47a4c239af8f0135f26e8f8ec55a724.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/09daf5f7124604cd69d333df02926f1e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/831a37d5c92f038275825b220b17798f.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a93130ed46257df6e210c7d9a820825e.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/d76bfbd12b1dd4ac5da8ac19001b8ff0.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ba25727ce85706400f7f926d25043ea1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/ff2439a7276e536f275266a1632982a2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/73c021da98c14a47164e0f5026a63280.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a964f85f00fc56f7a5a4957087b927af.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/597253533f8c4cb2951815b6ce581891.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"136127\",\n \"name\": \"Elaine Pedroso de Oliveira\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"04286-000\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"1379\",\n \"zone\": \"\",\n \"street\": \"Rua Coronel Francisco Inácio\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Vila Moinho Velho\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"11981182245\",\n \"alternative\": \"\",\n \"primary\": \"11981182245\"\n },\n \"logoUrl\": \"\",\n \"licenseNumber\": \"133870-F-SP\",\n \"websiteUrl\": \"\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T19:22:50Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1041554133\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 125m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-125m2-venda-RS1100000-id-1041554133/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/136127/elaine-pedroso-de-oliveira/\",\n \"rel\": \"\"\n }\n }\n },\n {\n \"listing\": {\n \"amenities\": [],\n \"feedsId\": \"PE7352\",\n \"usableAreas\": [\n 100\n ],\n \"description\": \"As informações contidas neste anúncio, tais como valor do imóvel, do condomínio e IPTU, poderão sofrer alterações.\",\n \"listingType\": \"USED\",\n \"title\": \"Apartamento, Pinheiros - São Paulo\",\n \"createdAt\": \"2018-09-06T05:28:31.952Z\",\n \"publisherId\": 51664,\n \"unitTypes\": [\n \"APARTMENT\"\n ],\n \"providerId\": \"15460\",\n \"condominiumName\": \"\",\n \"propertyType\": \"UNIT\",\n \"contact\": {\n \"chat\": \"\",\n \"phones\": [\n \"1138233545\",\n \"1138233545\"\n ],\n \"emails\": []\n },\n \"listingStatus\": \"ACTIVE\",\n \"id\": \"1040842685\",\n \"parkingSpaces\": [\n 1\n ],\n \"updatedAt\": \"2019-06-07T22:46:39.645Z\",\n \"owner\": False,\n \"address\": {\n \"country\": \"Brasil\",\n \"state\": \"São Paulo\",\n \"city\": \"São Paulo\",\n \"neighborhood\": \"Pinheiros\",\n \"street\": \"Rua Oscar Freire\",\n \"unitNumber\": \"\",\n \"zipCode\": \"05409010\",\n \"locationId\": \"BR>Sao Paulo>NULLZona Oeste>Pinheiros\",\n \"zone\": \"Zona Oeste\",\n \"district\": \"\",\n \"geoLocation\": {\n \"location\": {\n \"lat\": -23.558882,\n \"lon\": -46.673089\n },\n \"precision\": \"ROOFTOP\",\n \"optionalPrecision\": \"precision\"\n }\n },\n \"suites\": [\n 1\n ],\n \"publicationType\": \"STANDARD\",\n \"externalId\": \"PE7352\",\n \"bathrooms\": [\n 2\n ],\n \"totalAreas\": [\n 120\n ],\n \"logoUrl\": \"\",\n \"bedrooms\": [\n 3\n ],\n \"promotions\": [],\n \"highlights\": \"\",\n \"pricingInfos\": [\n {\n \"yearlyIptu\": \"370\",\n \"price\": \"1200000\",\n \"businessType\": \"SALE\",\n \"monthlyCondoFee\": \"1400\"\n }\n ],\n \"showPrice\": True,\n \"displayAddress\": \"STREET\",\n \"buildings\": 0,\n \"images\": [\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/475ffc182149abcc9692c3cf34e63c4b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/44830d9a2344f74a6b6f49188b0fe1d7.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/19c63b4d5279b1777a0888b69515e420.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a025e8e7a8315d8ae0515160568be317.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/af61906757a23bd7e9ed460e29390fb4.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/2d3a547bf3bddafe776f0450b06887cd.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8adeae7f8ea7c29aa3e90430d36e3871.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/6ef76e9c490bedc7c532ab2b7bdda70b.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/900cc1ee7337512003c7e9b2726a992d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/30e83bdc3f5e1c29f7ea18e24ee32d55.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/22cbb81501f9e9ab7312943fdfa358cb.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/bd80e202e71200e25b28f5b3c1a0d9a6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a2d745f51b869692796ca5724e0286d2.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4800b08bfd579fb7be4ddb7b1ca9f4c1.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/78009fd1bcf53c4771580fbab1f7dd34.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a602ef3e52d7e27322de62d6e98caf35.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/a1cf516b6d146ef4cb5f43456ced926d.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/8a44791aff9f2e79d0fac5e8657a77c6.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/4c83efd130a4ffd7750b34b8d3eaeb08.jpg\",\n \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/5512eb81bfaa0c30ec6bc2456f38ad8f.jpg\"\n ],\n \"videos\": []\n },\n \"publisher\": {\n \"id\": \"51664\",\n \"name\": \"JAIME ADMINISTRACAO DE BENS E CONDOMINIOS LTDA\",\n \"address\": {\n \"country\": \"Brasil\",\n \"zipCode\": \"01243-001\",\n \"city\": \"São Paulo\",\n \"streetNumber\": \"51664\",\n \"zone\": \"\",\n \"street\": \"Rua Sergipe\",\n \"locationId\": \"\",\n \"district\": \"\",\n \"unitNumber\": \"\",\n \"state\": \"SP\",\n \"neighborhood\": \"Consolação\"\n },\n \"phone\": {\n \"leadsPhone\": \"\",\n \"mobile\": \"1138233545\",\n \"alternative\": \"\",\n \"primary\": \"1138233545\"\n },\n \"logoUrl\": \"https://resizedimgs.vivareal.com/{action}/{width}x{height}/vr.images.sp/1db36cde5c31c37c2e1265b00d67e73f.jpg\",\n \"licenseNumber\": \"015908-J-SP\",\n \"websiteUrl\": \"http://www.jaime.com.br\",\n \"leadEmails\": [],\n \"createdDate\": \"2018-03-27T17:06:14Z\",\n \"showAddress\": True\n },\n \"url\": {\n \"id\": \"1040842685\",\n \"link\": {\n \"name\": \"Apartamento com 3 Quartos à venda, 100m²\",\n \"href\": \"/imovel/apartamento-3-quartos-pinheiros-zona-oeste-sao-paulo-com-garagem-100m2-venda-RS1200000-id-1040842685/\",\n \"rel\": \"\"\n }\n },\n \"properAddress\": None,\n \"publisherUrl\": {\n \"link\": {\n \"name\": \"\",\n \"href\": \"/51664/jaime-administracao-de-bens-e-condominios-ltda/\",\n \"rel\": \"\"\n }\n }\n }\n ]","sub_path":"app/services/crawler_data_territorio/mocks/listing_filtered.py","file_name":"listing_filtered.py","file_ext":"py","file_size_in_byte":95791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"476277067","text":"import datetime\nimport calendar\nimport wx\nimport wx.grid\n\n\ndef calendarText():\n \"\"\"example return:\n\n January 2016\n Mo Tu We Th Fr Sa Su\n 1 2 3\n 4 5 6 7 8 9 10\n 11 12 13 14 15 16 17\n 18 19 20 21 22 23 24\n 25 26 27 28 29 30 31\n \"\"\"\n\n now = datetime.datetime.now()\n x=\"%d\" %now.year\n y=\"%d\" %now.month\n\n yy=int(x)\n mm=int(y)\n return (calendar.month(yy,mm))\n\ndef calendarTextToListForGrid(text):\n \"\"\"example return:\n [' January 2016',\n ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'],\n [' ', ' ', ' ', ' ', ' 1', ' 2', ' 3'],\n [' 4', ' 5', ' 6', ' 7', ' 8', ' 9', ' 10'],\n ['11', ' 12', ' 13', ' 14', ' 15', ' 16', ' 17'],\n ['18', ' 19', ' 20', ' 21', ' 22', ' 23', ' 24'],\n ['25', ' 26', ' 27', ' 28', ' 29', ' 30', ' 31'],\n ['']]\n\n \"\"\"\n array = text.split(\"\\n\")\n output = []\n output.append(array[0])\n output.append(array[1].split(\" \"))\n for i in range(2, len(array)):\n listHelp = []\n string = array[i]\n listHelp.append(string[0:2])\n for j in range(2, len(string), 3):\n listHelp.append(string[j:j+3])\n output.append(listHelp)\n return output\n\n# uncomment these to test code:\n#test calendarTextToListForGrid(text)\n#print calendarTextToListForGrid(calendarText())\n\n\n\ncalendarList = calendarTextToListForGrid(calendarText())\nclass SimpleCalendarGrid(wx.grid.Grid):\n def __init__(self, parent):\n wx.grid.Grid.__init__(self, parent, -1)\n\n self.CreateGrid(5, 7)\n for j in range(7):\n self.SetColLabelValue(j, calendarList[1][j])\n for i in range(5):\n week = \"week \"+str(i+1)\n self.SetRowLabelValue(i, week)\n try:\n for j in range(7):\n cellValue = calendarList[i+2][j]\n self.SetCellValue(i, j, cellValue)\n except IndexError:\n for j in range(7):\n cellValue = calendarList[i+1][j]\n self.SetCellValue(i, j, cellValue)\n\nclass TestFrame(wx.Frame):\n def __init__(self, parent):\n frameTitle = calendarList[0]\n testFrame = wx.Frame.__init__(self, parent, -1, frameTitle, size=(650, 160), style=wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.CAPTION)\n\n #load application's icon\n self.icon = wx.Icon('mediaFilesPackage/calendar.ico', wx.BITMAP_TYPE_ICO)\n self.SetIcon(self.icon)\n\n grid = SimpleCalendarGrid(self)\n\n\nappCalendar = wx.App()\nframe = TestFrame(None)\nframe.Show(True)\nappCalendar.MainLoop()\n","sub_path":"codeFilesPackage/calendarSimpleText.pyw","file_name":"calendarSimpleText.pyw","file_ext":"pyw","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"294719027","text":"# 使下列代码循环执行,按e键退出\nwhile True:\n season = input(\"请输入:\")\n if season == \"春\":\n print(\"1月2月3月\")\n elif season == \"夏\":\n print(\"4月5月6月\")\n elif season == \"秋\":\n print(\"7月8月9月\")\n elif season == \"冬\":\n print(\"10月11月12月\")\n if input(\"输入e键退出:\") == \"e\":\n break # 退出循环体\n","sub_path":"study/1905/month01/code/Stage1/day03/exercise08.py","file_name":"exercise08.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"302339313","text":"\"\"\"\n\n选择排序\n 选择排序(Selection-sort)是一种简单直观的排序算法。它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,\n 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。\n\n 算法描述\n n个记录的直接选择排序可经过n-1趟直接选择排序得到有序结果。具体算法描述如下:\n\n 初始状态:无序区为R[1..n],有序区为空;\n 第i趟排序(i=1,2,3…n-1)开始时,当前有序区和无序区分别为R[1..i-1]和R(i..n)。该趟排序从当前无序区中-选出关键字最小的记录 R[k],将它与无序区的第1个记录R交换,使R[1..i]和R[i+1..n)分别变为记录个数增加1个的新有序区和记录个数减少1个的新无序区;\n n-1趟结束,数组有序化了。\n\n 算法分析\n 表现最稳定的排序算法之一,因为无论什么数据进去都是O(n2)的时间复杂度,所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。\n 理论上讲,选择排序可能也是平时排序一般人想到的最多的排序方法了吧。\n\n\"\"\"\n\n\nclass Solution:\n def select_sort(self, nums: list) -> list:\n length = len(nums)\n if length == 0:\n return nums\n\n variant_index = 0\n while variant_index < length:\n min_value_index = variant_index\n\n for i in range(variant_index, length):\n if nums[i] < nums[min_value_index]:\n min_value_index = i\n\n if min_value_index != variant_index:\n temp = nums[min_value_index]\n nums[min_value_index] = nums[variant_index]\n nums[variant_index] = temp\n\n variant_index += 1\n\n return nums\n\n\nif __name__ == '__main__':\n array = [1, 323, 4, 1, 5, 6, 8, 9, 113]\n solution = Solution()\n print(solution.select_sort(array))\n","sub_path":"python/sort/select_sort.py","file_name":"select_sort.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"562949970","text":"import h5py\nfrom dlgo.encoders import oneplane\nfrom dlgo.networks import large\nfrom dlgo.agent import pg\nfrom dlgo.agent import naive\nfrom dlgo import goboard_slow as goboard\nfrom dlgo import gotypes\nfrom dlgo import scoring\nfrom dlgo.rl import experience\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Activation\n\nimport time\n\nboard_size = (19,19)\n\nencoder = oneplane.OnePlaneEncoder(board_size)\nmodel = Sequential()\nfor layer in large.layers(encoder.shape()):\n model.add(layer)\nmodel.add(Dense(encoder.num_points()))\nmodel.add(Activation('softmax'))\n\n\nagent1 = pg.PolicyAgent(model, encoder)\nagent2 = pg.PolicyAgent(model, encoder)\ncollector1 = experience.ExperienceCollector()\ncollector2 = experience.ExperienceCollector()\nagent1.set_collector(collector1)\nagent2.set_collector(collector2)\n\nwith h5py.File('/home/bart/output_file1.h5', 'w') as outf:\n agent1.serialize(outf)\nwith h5py.File('/home/bart/output_file2.h5', 'w') as outf:\n agent2.serialize(outf)\n\n\na = []\n\nCOLS = 'ABCDEFGHJKLMNOPQRST'\nSTONE_TO_CHAR = {\nNone: ' . ',\ngotypes.Player.black: ' x ',\ngotypes.Player.white: ' o ',\n}\n\n\ndef print_move(player, move):\n if move.is_pass:\n move_str = 'passes'\n elif move.is_resign:\n move_str = 'resigns'\n else:\n move_str = '%s%d' % (COLS[move.point.col - 1], move.point.row)\n print('%s %s' % (player, move_str))\n \ndef print_board(board):\n for row in range(board.num_rows, 0, -1):\n bump = \" \" if row <= 9 else \"\"\n line = []\n for col in range(1, board.num_cols + 1):\n stone = board.get(gotypes.Point(row=row, col=col))\n line.append(STONE_TO_CHAR[stone])\n print('%s%d %s' % (bump, row, ''.join(line)))\n print(' ' + ' '.join(COLS[:board.num_cols]))\n\ndef main():\n board_size = 19\n game = goboard.GameState.new_game(board_size)\n bots = {\n #gotypes.Player.black: naive.RandomBot(),\n gotypes.Player.black: agent1,\n gotypes.Player.white: agent2,\n \n }\n while not game.is_over():\n time.sleep(0.3) # <1>\n\n print(chr(27) + \"[2J\") # <2>\n print_board(game.board)\n bot_move = bots[game.next_player].select_move(game)\n print_move(game.next_player, bot_move)\n game = game.apply_move(bot_move)\n \n game_result = scoring.compute_game_result(game)\n print(\"and the winner is:\",game_result.winner)\n a.append(game_result.winner)\n return game_result.winner\n\n\nnum_games = 1\n\nfor i in range(num_games):\n collector1.begin_episode()\n collector2.begin_episode()\n \n game_record = main()\n\n if a[0] == 'Player.black':\n collector1.complete_episode(reward=1)\n collector2.complete_episode(reward=-1)\n else:\n collector2.complete_episode(reward=1)\n collector1.complete_episode(reward=-1)\n\nexp = experience.combine_experience([collector1,collector2])\n\nwith h5py.File('/home/bart/experience_file.h5', 'w') as experience_outf:\n exp.serialize(experience_outf)\n\n\n\n","sub_path":"ReinforcementLearning/rl/go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"366509605","text":"from ScanQRcodePyGame import getQRCode\nfrom AttendanceSheet import Sheet\nfrom GroupList import GroupList\nfrom QRList import QRList\nimport pifacecad\nimport time\nimport sys\n\nWAITING, SELECTING_GROUP, ASK_FOR_DOWNLOAD, ATTENDANCE_SCANNING, PRESENTATION_SCANNING = range(0, 5)\nstate = WAITING\nselectedGroup = 0\n\ndef update_pin(event):\n\tglobal state\n\tglobal selectedGroup\n\tglobal groupList\n\tglobal qrList\n\tglobal sheet\n\tprint(\"main pressed \"+str(state)+\" \"+str(event.pin_num))\n\tif state == ASK_FOR_DOWNLOAD and event.pin_num == 0:\n\t\tevent.chip.lcd.clear()\n\t\tevent.chip.lcd.write(\"Downloading...\")\n\t\tgroupList.download()\n\t\tqrList.download()\n\t\tstate = SELECTING_GROUP\n\t\tupdate_group_selection()\n\t\treturn\n\tif state == ASK_FOR_DOWNLOAD and event.pin_num == 1:\n\t\tgroupList.load()\n\t\tqrList.load()\n\t\tstate = SELECTING_GROUP\n\t\tupdate_group_selection()\n\t\treturn\n\n\tif state == SELECTING_GROUP and event.pin_num == 0:\n\t\tselectedGroup = (selectedGroup+1)%len(groupList.getGroups())\n\t\tupdate_group_selection()\n\t\treturn\n\tif state == SELECTING_GROUP and event.pin_num == 1:\n\t\tevent.chip.lcd.clear()\n\t\tevent.chip.lcd.write(str(groupList.getGroups()[selectedGroup])+\"!\")\n\t\ttime.sleep(2)\n\t\tstop_scanning()\n\t\treturn\n\n\tif state == WAITING and event.pin_num == 0:\n\t\tprint(\"att scan\")\n\t\tstate = ATTENDANCE_SCANNING\n\t\thandle_scanning()\n\t\treturn\n\tif state == WAITING and event.pin_num == 1:\n\t\tprint(\"pres scan\")\n\t\tstate = PRESENTATION_SCANNING\n\t\thandle_scanning()\n\t\treturn\n\tif state == WAITING and event.pin_num == 2:\n\t\tevent.chip.lcd.clear()\n\t\tevent.chip.lcd.set_cursor(0,0)\n\t\tevent.chip.lcd.write(\"Uploading...\")\n\t\tif sheet.upload():\n\t\t\tevent.chip.lcd.clear()\n\t\t\tevent.chip.lcd.write(\"Upload successful\")\n\t\telse:\n\t\t\tevent.chip.lcd.clear()\n\t\t\tevent.chip.lcd.write(\"Upload failed\")\n\t\ttime.sleep(2)\n\t\tstop_scanning()\n\t\treturn\n\n\tif state == WAITING and event.pin_num == 3:\n\t\tsheet.save()\n\t\texit()\n\ndef update_group_selection():\n\tcad.lcd.clear()\n\tcad.lcd.write(str(groupList.getGroups()[selectedGroup])+\"?\")\n\tcad.lcd.set_cursor(0,1)\n\tcad.lcd.write(\"0:change 1:select\")\t\n\ndef handle_scanning():\n\tglobal state\n\tglobal sheet\n\tif state == ATTENDANCE_SCANNING:\n\t\twhile True:\n\t\t\tqrCode = getQRCode(\"attend.\");\n\t\t\tif qrCode == \"-1\":\n\t\t\t\tstop_scanning()\n\t\t\t\tbreak\n\t\t\tif qrCode is not \"0\":\n\t\t\t\tcad.lcd.clear()\n\t\t\t\tcad.lcd.set_cursor(0,0)\n\t\t\t\tif is_qr_valid(qrCode):\n\t\t\t\t\tcad.lcd.write(\"QR code valid\")\n\t\t\t\t\tprint(qrCode + \" is valid\")\n\t\t\t\t\tsheet.addAttendance(str(qrCode).split(\";\")[1])\n\t\t\t\telse:\n\t\t\t\t\tcad.lcd.write(\"QR code invalid\")\n\t\t\t\t\tprint(qrCode +\" is invalid\")\n\t\t\t\ttime.sleep(2)\n\n\tif state == PRESENTATION_SCANNING:\n\t\twhile True:\n\t\t\tqrCode = getQRCode(\"pres.\");\n\t\t\tif qrCode == \"-1\":\n\t\t\t\tstop_scanning()\n\t\t\t\tbreak\n\t\t\tif qrCode is not \"0\":\n\t\t\t\tcad.lcd.clear()\n\t\t\t\tcad.lcd.set_cursor(0,0)\n\t\t\t\tif is_qr_valid(qrCode):\n\t\t\t\t\tcad.lcd.write(\"QR code valid\")\n\t\t\t\t\tprint(qrCode + \" is valid\")\n\t\t\t\t\tsheet.addPresentation(str(qrCode).split(\";\")[1])\n\t\t\t\telse:\n\t\t\t\t\tcad.lcd.write(\"QR code invalid\")\n\t\t\t\t\tprint(qrCode +\" is invalid\")\n\t\t\t\ttime.sleep(2)\n\t\t\t\tstop_scanning()\n\t\t\t\tbreak\n\n\ndef stop_scanning():\n\tglobal state\n\tprint(\"Scanning stopped\")\n\tcad.lcd.clear()\n\tcad.lcd.set_cursor(0,0)\n\tcad.lcd.write(\"0:att. 1:pres.\")\n\tcad.lcd.set_cursor(0,1)\n\tcad.lcd.write(\"2:upload\")\n\tstate = WAITING\n\ndef is_qr_valid(qr):\n\treturn qr.split(\";\")[2] == groupList.getGroups()[selectedGroup] and qrList.is_qr_valid(qr)\n\ncad = pifacecad.PiFaceCAD()\ncad.lcd.backlight_on()\n\nlistener = pifacecad.SwitchEventListener(chip=cad)\nfor i in range(8):\n\tlistener.register(i, pifacecad.IODIR_FALLING_EDGE, update_pin)\nlistener.activate()\n\n#groupList = getGroupList()\ncad.lcd.write(\"Download files?\")\ncad.lcd.set_cursor(0,1)\ncad.lcd.write(\"0:yes 1:no\")\ncad.lcd.set_cursor(0,0)\nstate = ASK_FOR_DOWNLOAD\n\nsheet = Sheet()\ngroupList = GroupList()\nqrList = QRList()","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"152219812","text":"# -*- coding: utf-8 -*-\nimport os,sys\nimport pandas as pd\nimport numpy as np\n#import pandas.io.data as web\nimport time\n#from datetime import*\n#可以循环获得你想要的股票代码的行情数据,只是近3年的数据\ndef yahoodatasettlement():\n code_list = []\n for root, dirs, files in os.walk('./stockdata/yahoo/'):# 注意:这里请填写数据文件在您电脑中的路径\n if files:\n for f in files:\n if '.csv' in f:\n code_list.append(f.split('.csv')[0])\n for code in code_list:\n filename='./stockdata/yahoo/'+code+'.csv'\n stock_data = pd.read_csv(filename, parse_dates=['Date'])\n stock_data.sort('Date', inplace=True)\n stock_data['p_change']=(stock_data['Adj Close']/stock_data['Adj Close'].shift(1)-1)*100\n stock_data.columns = ['date','open','high','low','close','volume','adj_close','p_change']\n stock_data.to_csv(filename,index=False)\n return\n \nyahoodatasettlement()\n","sub_path":"jiaoben/yahoodatasettle.py","file_name":"yahoodatasettle.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"68470977","text":"parent = [('parent', 'manjur', 'sohel'), ('parent', 'manjur', 'tufel'),\n ('parent', 'manjur', 'jerin'), ('parent', 'manjur', 'najnin'),\n ('parent', 'tufel', 'rifat'), ('parent', 'jerin', 'raaj')]\n\nmale = [('male', 'manjur'), ('male', 'sohel'),\n ('male', 'tufel'), ('male', 'rifat'), ('male', 'raaj')]\n\nfemale = [('female', 'jerin'), ('female', 'najnin')]\n\ndef findBr(): #brother\n X = str(input(\"Sibling:\\n\"))\n print('Brother:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if (parent[i][0] == 'parent') & (parent[i][2] == X):\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[i][1]) & (parent[i][2]!=parent[j][2]):\n for k in range(len(male)):\n if(male[k][0]=='male') & (male[k][1]==parent[j][2]):\n print(male[k][1])\n bl = False\n if (bl):\n print('N\\A')\n\ndef findSr(): #sister\n X = str(input(\"Sibling:\\n\"))\n print('Sister:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if (parent[i][0] == 'parent') & (parent[i][2] == X):\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[i][1]) & (parent[i][2]!=parent[j][2]):\n for k in range(len(female)):\n if(female[k][0]=='female') & (female[k][1]==parent[j][2]):\n print(female[k][1])\n bl = False\n if(bl):\n print('N\\A')\n\ndef findUl(): #uncle\n X = str(input(\"Nephew:\\n\"))\n print('Uncle:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if(parent[i][0]=='parent') & (parent[i][2]==X):#parent[i][1] parent\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][2]==parent[i][1]):#parent[j][1] grandparent\n for k in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[k][1]) & (parent[i][1]!=parent[k][2]): #parent[k][2] parent's sibling\n for l in range(len(male)):\n if(male[l][0]=='male') & (male[l][1]==parent[k][2]): #male[l][1] uncle\n print(male[l][1])\n bl = False\n if(bl):\n print('N/A')\n\ndef findUt(): #aunt\n X = str(input(\"Nephew:\\n\"))\n print('Aunt:', end='\\n')\n bl = True\n for i in range(len(parent)):\n if(parent[i][0]=='parent') & (parent[i][2]==X):#parent[i][1] parent\n for j in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][2]==parent[i][1]):#parent[j][1] grandparent\n for k in range(len(parent)):\n if (parent[j][0] == 'parent') & (parent[j][1] == parent[k][1]) & (parent[i][1]!=parent[k][2]): #parent[k][2] parent's sibling\n for l in range(len(female)):\n if(female[l][0]=='female') & (female[l][1]==parent[k][2]): #female[l][1] aunt\n print(female[l][1])\n bl = False\n if(bl):\n print('N/A')\n\ndef Print():\n print('1: Brother, 2: Sister, 3: Uncle, 4: Aunt, Other character: Exit')\n x = input(\"press a character:\\n\")\n return x\n\nx = Print()\nwhile (1):\n if x == '1':\n findBr() #brother\n elif x == '2':\n findSr() #sister\n elif x == '3':\n findUl() #uncle\n elif x == '4':\n findUt() #aunt\n else:\n break\n x = Print()\n","sub_path":"AI/Python/Assignment_01_Q2.py","file_name":"Assignment_01_Q2.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"218721494","text":"from dictionary import *\n\n\ndef encrypt(message):\n cipher = ''\n for letter in message:\n if letter != ' ':\n cipher += code[letter] + ' '\n else:\n cipher += ' '\n return cipher\n\n\ndef decrypt(message):\n message += ' '\n\n decipher = ''\n citext = ''\n for letter in message:\n if letter != ' ':\n i = 0\n citext += letter\n else:\n i += 1\n if i == 2:\n decipher += ' '\n else:\n decipher += list(code.keys()\n )[list(code.values()).index(citext)]\n citext = ''\n return decipher\n","sub_path":"py/Morse/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"620366721","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('ffsq.views',\n url(r'^$', 'index', name='home'),\n url(r'^search/$', 'search', name='search'),\n url(r'^ranking/$', 'ranking', name='ranking'),\n url(r'^how_to_use/$', 'how_to_use', name='how_to_use'),\n url(r'^search_parks/$', 'search_parks', name='search_parks'),\n url(r'^parks/(?P\\d+)/$', 'park_detail', name='park_detail'),\n url(r'^parks/(?P\\d+)/review/$', 'park_review', name=\"park_review\"),\n url(r'^reviews/(?P\\d+)/$', 'review_edit', name=\"review_edit\"),\n url(r'^login$', 'login', name='login'),\n)\n\nurlpatterns += patterns('',\n url(r'^logout/$', 'django.contrib.auth.views.logout', {\n 'template_name': 'ffsq/logged_out.html'\n }, name='logout'),\n url(r'', include('social_auth.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"ffsq/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"301117048","text":"\"\"\"alex_project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import re_path\nfrom .views import PostListView, PostDetailView, CategorieListView\n\nurlpatterns = [\n re_path(r'^blog/home/(?P\\d+)$', PostListView.as_view(),\n name='blog_home_page'),\n re_path(r'^blog/categorie/(?P\\w+)/(?P\\d+)$',\n CategorieListView.as_view(), name='blog_custom_page'),\n re_path(\n r'^blog/post/(?P.+)-(?P\\d+)$',\n PostDetailView.as_view(),\n name='detail_post'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"559961265","text":"# -*- coding:utf-8 -*-\n\n# #\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110- 1301, USA.\n#\n# \n# \n\n# Copyright (c) 2004-2011 Bruno Postle .\n\n# ----------------------------------------------------------\n# Author: Bruno Postle \n# Python translation: Stephen Leger (s-leger)\n#\n# ----------------------------------------------------------\n\n'''\nUrb::Boundary - A division within a quadrilateral space\n\nModels a division within an Urb::Quad object and child quads that share this boundary\n\nA boundary is a division of a quad or the edge of the root quad, it is always a\nstraight line. It has various leafnode quads attached to it. The boundary\nobject is a list of references to these leafnodes in no particular order.\n\n'''\n\n\nfrom math import pi\nfrom .math import distance_2d, angle_2d\n\n\nclass Boundary(list):\n\n def __init__(self):\n list.__init__(self)\n\n\n def add_edges(self, quad, id_edge):\n '''Attach a quad to this boundary, indicate which edge of the quad (0,1,2 or 3) is attached:\n boundary->Add_Edge ($quad, 2);\n '''\n self.append({quad: quad, id_edge: id_edge})\n\n @property\n def _id(self):\n '''Query the Id of the quad of which this boundary is a division\n :return: boundary_id\n '''\n if len(self) < 1:\n return\n ed = self[0]\n return ed['quad'].boundary_id(ed['id_edge'])\n\n @property\n def length_total(self):\n '''Query the total length of this boundary\n :return: length_total\n '''\n quad_parent = self[0]['quad'].by_id(self._id)\n return distance_2d(quad_parent.coordinate_a, quad_parent.coordinate_b)\n\n @property\n def is_valid(self):\n '''Check some internal consistency\n :return: boolean validate_id\n '''\n _id = self._id\n for item in self:\n if _id != item['quad'].boundary_id(item['id_edge']):\n return False\n return True\n\n def _find_edges(self, quad_a, quad_b):\n edge_a, edge_b = None, None\n for item in self:\n if item['quad'] is quad_a:\n edge_a = item['id_edge']\n if item['quad'] is quad_b:\n edge_b = item['id_edge']\n return edge_a, edge_b\n\n def overlap(self, quad_a, quad_b):\n '''Given two quads, find out how much they overlap on this boundary, if at all\n :param quad_a:\n :param quad_b:\n :return: distance = boundary->Overlap (quad_a, quad_b)\n '''\n edge_a, edge_b = self._find_edges(quad_a, quad_b)\n if edge_a is None or edge_b is None:\n return 0.0\n\n if not self._id in {'a', 'b', 'c', 'd'}:\n return 0.0\n\n _id = self._id\n\n if quad_a.boundary_id(edge_a) != _id or \\\n quad_b.boundary_id(edge_b) != _id:\n return 0.0\n\n length_a = quad_a.length(edge_a)\n length_b = quad_b.length(edge_b)\n ca0, ca1 = quad_a.coordinate(edge_a), quad_a.coordinate(edge_a + 1)\n cb0, cb1 = quad_b.coordinate(edge_b), quad_b.coordinate(edge_b + 1)\n\n d = max(\n distance_2d(ca0, cb0),\n distance_2d(ca0, cb1),\n distance_2d(ca1, cb0),\n distance_2d(ca1, cb1)\n )\n\n if d <= length_b:\n return length_a\n\n if d <= length_a:\n return length_b\n\n return length_a + length_b - d\n\n def coordinates(self, quad_a, quad_b):\n '''Query coordinates of the segment shared by two overlapping quads\n :param quad_a:\n :param quad_b:\n :return: xy1 xy2 or None\n '''\n edge_a, edge_b = self._find_edges(quad_a, quad_b)\n if edge_a is None or edge_b is None:\n return\n _id = self._id\n if quad_a.boundary_id(edge_a) != _id or \\\n quad_b.boundary_id(edge_b) != _id:\n return\n if self.overlap(quad_a, quad_b) <= 0:\n return\n length_a = quad_a.length(edge_a)\n length_b = quad_b.length(edge_b)\n ca0, ca1 = quad_a.coordinate(edge_a), quad_a.coordinate(edge_a + 1)\n cb0, cb1 = quad_b.coordinate(edge_b), quad_b.coordinate(edge_b + 1)\n\n length = distance_2d(ca0, cb0)\n ea, eb = edge_a + 1, edge_b + 1\n qa, qb = quad_a, quad_b\n\n d = distance_2d(ca0, cb1)\n if d > length:\n length = d\n ea, eb = edge_a + 1, edge_b\n\n d = distance_2d(ca1, cb0)\n if d > length:\n length = d\n ea, eb = edge_a, edge_b + 1\n\n d = distance_2d(ca1, cb1)\n if d > length:\n length = d\n ea, eb = edge_a, edge_b\n\n # edge_a is contained entirely within edge_b\n if length < length_b:\n ea, eb = edge_a, edge_a + 1\n qb = quad_a\n\n # edge_a is contained entirely within edge_a\n if length < length_a:\n ea, eb = edge_b, edge_b + 1\n qa = quad_b\n\n # otherwise edge_a and edge_b partially overlap so we want the two inner points\n c0, c1 = qa.coordiates(ea), qb.coordinates(eb)\n rad_quads = angle_2d(quad_a.centroid, quad_b.centroid)\n rad_edge = angle_2d(c1, c0)\n rad = rad_edge - rad_quads\n if rad > pi:\n return c0, c1\n else:\n return c1, c0\n\n def bearing(self, quad_a, quad_b):\n '''Query perpendicular bearing between centre quad and boundary with other quad,\n i.e. if this boundary is a wall, which direction does it face (east = 0.0, north = 1.57):\n :param quad_a:\n :param quad_b:\n :return: radians\n '''\n coor_a, coor_b = self.coordinates(quad_a, quad_b)\n centroid = quad_a.centroid\n angle_a = angle_2d(centroid, coor_a)\n angle_b = angle_2d(centroid, coor_b)\n\n angle = (angle_a - angle_b) % (2 * pi)\n # TODO: check for the % method\n angle_wall = angle_2d(coor_a, coor_b) % (2 * pi)\n if angle < pi / 2:\n angle_wall = angle_2d(coor_b, coor_a) % (2 * pi)\n return angle_wall\n\n def middle(self, quad_a, quad_b):\n '''Query the mid point of an edge half way up\n :param quad_a:\n :param quad_b:\n :return: tuple coor 3d\n '''\n coor_a, coor_b = self.coordinates(quad_a, quad_b)\n return 0.5 * (coor_a[0] + coor_b[0]), 0.5 * (coor_a[1] + coor_b[1]), quad_a.elevation + 0.5 * quad_a.height\n\n @property\n def pairs(self):\n '''Get a list of all pairs of quads that have a segment that is part of this boundary\n :return: list of pairs of quads\n '''\n if self._id is None or not not self._id in {'a', 'b', 'c', 'd'}:\n return []\n pairs = []\n for index_a, item_a in enumerate(self[:-1]):\n quad_a = item_a['quad']\n for item_b in self[index_a + 1:]:\n quad_b = item_b['quad']\n if self.overlap(quad_a, quad_b) > 0:\n pairs.append([quad_a, quad_b])\n return pairs\n\n @property\n def pairs_by_length(self):\n '''Get a list of all pairs as with Pairs(), but sorted by length of shared segment\n :return: list of pairs of quads\n '''\n pairs = self.pairs\n pairs.sort(key=lambda x: self.overlap(x[0], x[1]))\n return pairs\n","sub_path":"urb/boundary.py","file_name":"boundary.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"319204591","text":"import numpy as np\nimport time\nimport matplotlib.pyplot as plt\nimport warnings\nimport sys\n\n\n#Imports relacionados con Machine Learning, métricas,preprocesado de datos..clasificadores.\nfrom sklearn.preprocessing import normalize\nfrom sklearn.model_selection import cross_val_score, cross_val_predict, ShuffleSplit, train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import zero_one_loss\nfrom sklearn.ensemble import AdaBoostClassifier\n\n#Datos de la base de datos para realizar la clasificación\ndatos = np.genfromtxt('muestra_datos.csv', delimiter = ';')\ndigitos = normalize(datos[:, :-1])\netiquetas = datos[:, -1]\n\nx_train, x_eval, y_train, y_eval = train_test_split(digitos, etiquetas, test_size=0.3,\n train_size=0.7,\n random_state=1982)\nn_estimators = 400\n\n#Instancias de los clasificadores y entrenamiento\nclf_stump = DecisionTreeClassifier(max_depth=1, min_samples_leaf=1) #Stump significa tocón\nclf_stump.fit(x_train, y_train)\nclf_stump_err = 1-clf_stump.score(x_eval, y_eval)\nprint('Error del tocón'+str(clf_stump_err))\nclf_tree = DecisionTreeClassifier(max_depth=9, min_samples_leaf=1)\nclf_tree.fit(x_train, y_train)\nclf_tree_err = 1-clf_tree.score(x_eval, y_eval)\nprint('Error del árbol de decisión'+str(clf_tree_err))\nclf_adaBoostdis = AdaBoostClassifier(base_estimator=clf_stump, learning_rate=1, n_estimators=n_estimators, algorithm=\"SAMME\") #AdaBoost discreto\nclf_adaBoostreal = AdaBoostClassifier(base_estimator=clf_stump, learning_rate=1, n_estimators=n_estimators, algorithm=\"SAMME.R\")\nclf_adaBoostdis.fit(x_train, y_train)\nclf_adaBoostreal.fit(x_train, y_train)\n\n#plots\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot([1, n_estimators], [clf_stump_err] * 2, 'k-',\n label='Decision stump Error')\nax.plot([1, n_estimators], [clf_tree_err] * 2, 'k--',\n label='Decision Tree Error')\n\n#Errores del AdaBoost real y discreto para los valores de entrenamiento y de testeo\nada_discrete_err = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostdis.staged_predict(x_eval)):\n ada_discrete_err[i] = zero_one_loss(y_pred, y_eval)\n#print('AdaBdiscrete eval'+str(ada_discrete_err))\nada_discrete_err_train = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostdis.staged_predict(x_train)):\n ada_discrete_err_train[i] = zero_one_loss(y_pred, y_train)\n#print(('AdaBdiscrete train'+str(ada_discrete_err_train)))\nada_real_err = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostreal.staged_predict(x_eval)):\n ada_real_err[i] = zero_one_loss(y_pred, y_eval)\n#print('AdaBreal eval'+str(ada_real_err))\nada_real_err_train = np.zeros((n_estimators,))\nfor i, y_pred in enumerate(clf_adaBoostreal.staged_predict(x_train)):\n ada_real_err_train[i] = zero_one_loss(y_pred, y_train)\n\n#print('AdaBreal train'+str(ada_real_err_train))\nax.plot(np.arange(n_estimators) + 1, ada_discrete_err,\n label='Discrete AdaBoost Test Error',\n color='red')\nax.plot(np.arange(n_estimators) + 1, ada_discrete_err_train,\n label='Discrete AdaBoost Train Error',\n color='blue')\nax.plot(np.arange(n_estimators) + 1, ada_real_err,\n label='Real AdaBoost Test Error',\n color='orange')\nax.plot(np.arange(n_estimators) + 1, ada_real_err_train,\n label='Real AdaBoost Train Error',\n color='green')\n\nax.set_ylim((0.0, 1))\nax.set_xlabel('n_estimators')\nax.set_ylabel('error rate')\n\nleg = ax.legend(loc='upper right', fancybox=True)\nleg.get_frame().set_alpha(0.7)\n\nplt.show()\n","sub_path":"libs/pruebasboost.py","file_name":"pruebasboost.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"267870542","text":"import os\nimport ROOT\nimport json\nimport sys\nfrom collections import OrderedDict\nimport numpy as np\nimport math\n\nplotdir = \"/eos/user/t/tihsu/DataAnalysis/Charge_Flip_woSB_nanoaod/\"\ntag = 'combine'\nori_detail = False\n# Read Files\nworkdir = os.getcwd()\ntargetdir = os.path.join(\"/eos/user/t/tihsu/output_ntuple_2/\")\nAllfile = os.listdir(targetdir)\n\n# Read json Files\njsonfile = open(os.path.join(workdir+\"/../samples_2017_nanoaod.json\"))\nsamplesList = json.load(jsonfile,encoding = 'utf-8', object_pairs_hook=OrderedDict).items()\njsonfile.close()\n\n# Basic Setting\npt_region = np.array(( 20.0, 50.0, 100., 300.))\neta_region = np.array((0.0, 0.8, 1.479, 2.4))\npt_bins = len(pt_region)-1\neta_bins = len(eta_region)-1\nchannel = ['MC_os','MC_ss','data_os','data_ss','back_os','back_ss']\nNumber = dict()\nPij = dict()\nVij = dict()\nP_fit = dict()\n\nN_MC = 0.\nN_data = 0.\n\nfor ch in channel:\n Number[ch] = [[[[0. for i in range(eta_bins)] for j in range(pt_bins)] for ii in range(eta_bins)] for jj in range(pt_bins)]\n\n#skip_list = [\"MC13TeV_2017_QCDEM_120to170_2.root\", \"MC13TeV_2017_QCDEM_120to170_1.root\", \"MC13TeV_2017_QCDEM_80to120_1.root\",\"MC13TeV_2017_QCDEM_80to120_3.root\",\"MC13TeV_2017_QCDEM_120to170_4.root\",\"MC13TeV_2017_WJets_mlm_49.root\"]\nskip_list = []\n# Run Through All files\nfor s ,desc in samplesList:\n weight = desc[0]*41.5*1000\n for ff in Allfile:\n if s in ff:\n try:\n inf = ROOT.TFile.Open(os.path.join(targetdir+ff))\n try:\n t = inf.Get(\"TreeInput\")\n except:\n t = inf.Get(\"Chunks/\"+ff+\"/TreeInput\")\n n_entry = t.GetEntries()\n if \"MC\" in s and (desc[3] == \"DY\" or desc[3]==\"t#bar{t}\"):\n print(\"Signal: \"+ff)\n t.GetEntry(0)\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n Number['MC_ss'][i][j][ii][jj] += t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]*weight\n Number['MC_os'][i][j][ii][jj] += t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]*weight\n if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):\n print(\"******* \"+str(jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i)+str(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]))\n N_MC += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight + float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n elif \"Data\" in s:\n print(\"Data: \"+ff)\n t.GetEntry(0)\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n Number['data_ss'][i][j][ii][jj] += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])\n Number['data_os'][i][j][ii][jj] += float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])\n N_data += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]) + float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])\n if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):\n print(\"******* \"+str(jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i)+str(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i]))\n elif(ff not in skip_list):\n print(\"Background: \"+ff)\n t.GetEntry(0)\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n #if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):continue\n #if (math.isnan(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):continue\n Number['back_ss'][i][j][ii][jj] += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n Number['back_os'][i][j][ii][jj] += float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n if (math.isnan(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])):\n print(\"******* \"+str(jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i)+str(float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])))\n N_MC += float(t.t_Nss[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight + float(t.t_Nos[jj+eta_bins*ii+eta_bins*pt_bins*j+eta_bins*pt_bins*eta_bins*i])*weight\n inf.Close()\n except:\n print(ff+\"-->Trigger exception\")\nprint(N_data)\nprint(N_MC)\nnormscale = 1.\n\"\"\"for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n N_MC += Number['MC_ss'][i][j][ii][jj]\n N_MC += Number['MC_os'][i][j][ii][jj]\n N_data += Number['data_ss'][i][j][ii][jj]\n N_data += Number['data_os'][i][j][ii][jj]\n N_MC += Number['back_ss'][i][j][ii][jj]\n N_MC += Number['back_os'][i][j][ii][jj]\n\"\"\"\nprint(N_data)\nprint(N_MC)\nnormscale = N_data/N_MC\nprint(normscale)\nnormscale = 1.\nfor i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n Number['MC_ss'][i][j][ii][jj]*=normscale\n Number['MC_os'][i][j][ii][jj]*=normscale\n Number['data_ss'][i][j][ii][jj]-=Number['back_ss'][i][j][ii][jj]*normscale\n Number['data_os'][i][j][ii][jj]-=Number['back_os'][i][j][ii][jj]*normscale\n\n# Combine symmetric result\nfor h in Number:\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if(ii>i or jj>j):\n Number[h][ii][jj][i][j]+=Number[h][i][j][ii][jj]\n Number[h][i][j][ii][jj] = 0\n\n# Combine 100-200GeV with 200 GeV up\nif(tag=='combine' and ori_detail):\n pt_region = np.array(( 20.0, 50.0, 100.0, 300.))\n eta_region = np.array((0.0,0.8,1.479, 2.4))\n pt_bins = len(pt_region)-1\n eta_bins = len(eta_region)-1\n for h in Number:\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if(i==pt_bins-1 and ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii+1][jj]\n Number[h][i+1][j][ii+1][jj] = 0\n if(i==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii][jj]\n Number[h][i+1][j][ii][jj] = 0\n if(ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i][j][ii+1][jj]\n Number[h][i][j][ii+1][jj] = 0\nif(tag=='combine' and ori_detail):\n pt_region = np.array(( 20.0, 50.0, 100.0, 300.))\n eta_region = np.array((0.0, 1.479, 2.4))\n pt_bins = len(pt_region)-1\n eta_bins = len(eta_region)-1\n for h in Number:\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if(i==pt_bins-1 and ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii+1][jj]\n Number[h][i+1][j][ii+1][jj] = 0\n if(i==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i+1][j][ii][jj]\n Number[h][i+1][j][ii][jj] = 0\n if(ii==pt_bins-1):\n Number[h][i][j][ii][jj] += Number[h][i][j][ii+1][jj]\n Number[h][i][j][ii+1][jj] = 0\n\nP_fit['data'] = [[0. for i in range(eta_bins)] for j in range(pt_bins)]\nP_fit['MC'] = [[0. for i in range(eta_bins)] for j in range(pt_bins)]\nSF = [[0. for i in range(eta_bins)] for j in range(pt_bins)]\n\n# Calculate Probability\nDvMC = ['data','MC']\nfor h in DvMC:\n Pij[h] = [[[[0. for i in range(eta_bins)] for j in range(pt_bins)] for ii in range(eta_bins)] for jj in range(pt_bins)]\n Vij[h] = [[[[0. for i in range(eta_bins)] for j in range(pt_bins)] for ii in range(eta_bins)] for jj in range(pt_bins)]\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n# print(\"l1_pt = \" + str(pt_region[i]) + \" l1_eta = \" + str(eta_region[j]) + \" l2_pt = \" + str(pt_region[ii]) + \" l2_eta = \" + str(eta_region[jj]))\n# print('ss : '+str(Number[h+'_ss'][i][j][ii][jj])+' os : '+str(Number[h+'_os'][i][j][ii][jj]))\n if(1):\n N_ss = Number[h+'_ss'][i][j][ii][jj]\n N_T = N_ss + Number[h+'_os'][i][j][ii][jj] \n if(N_T>0. and N_ss>0.):\n Pij[h][i][j][ii][jj] = N_ss/N_T\n Vij[h][i][j][ii][jj] = N_ss/(N_T**2)+(N_ss**2)/(N_T**3)-2*(N_ss**1.5)/(N_T**2.5)\n# Vij[h][i][j][ii][jj] = N_ss/(N_T**2)+(N_ss**2)/(N_T**3) # without consider covariance \n else:\n print(\"raise Number counting error\")\n pass\nfor i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n print(str(i)+str(j)+str(ii)+str(jj)+\" : data: \"+str(Pij['data'][i][j][ii][jj])+\" MC: \"+str(Pij['MC'][i][j][ii][jj]))\n print(str(Number['data_os'][i][j][ii][jj])+\" \"+str(Number['MC_os'][i][j][ii][jj]))\n\n\n# Use chi2 to fit\n \nfor h in DvMC:\n print(Pij[h])\n gMinuit = ROOT.TMinuit(pt_bins*eta_bins)\n\n def fcn(npar, gin, f, par, iflag):\n chi2 = 0. \n Likelihood = 0.\n for i in range(pt_bins):\n for j in range(eta_bins):\n for ii in range(pt_bins):\n for jj in range(eta_bins):\n if (not Vij[h][i][j][ii][jj]==0.) and Number[h+'_os'][i][j][ii][jj]>200. and Number[h+'_ss'][i][j][ii][jj]>1.:\n P1 = par[i*eta_bins+j]\n P2 = par[ii*eta_bins+jj]\n eP = P1+P2-2.*P1*P2\n N = int(round(Number[h+'_os'][i][j][ii][jj]+Number[h+'_ss'][i][j][ii][jj]))\n Nsc = int(round(Number[h+'_ss'][i][j][ii][jj]))\n chi2 += ((Pij[h][i][j][ii][jj]-(P1+P2-2.*P1*P2))**2)/(Vij[h][i][j][ii][jj])\n Likelihood += Nsc*np.math.log((N*(eP)))-N*(eP)-np.math.log(np.math.factorial(Nsc))\n\n f[0] = -1.*Likelihood\n\n gMinuit.SetFCN(fcn)\n for i in range(pt_bins):\n for j in range(eta_bins):\n init_val = 0.0001\n if Number[h+'_os'][i][j][i][j]>5000:\n init_val = 1.-(1.-Pij[h][i][j][i][j])**0.5\n print(init_val)\n gMinuit.DefineParameter(i*eta_bins+j,\"P\"+str(i)+str(j),init_val,0.00000001,0.,0.1) \n gMinuit.Command(\"Minuit2\")\n# r = gMinuit.save()\n# Result Plot\n w = 600;\n he = 600;\n c = ROOT.TCanvas(h+'c','c',10,10,w,he)\n ROOT.gStyle.SetOptStat(\"kFALSE\")\n ROOT.gStyle.SetPaintTextFormat(\".2e\");\n ROOT.gStyle.SetPalette(69);\n ROOT.gStyle.SetCanvasBorderSize(0)\n ROOT.gStyle.SetCanvasBorderMode(0)\n ROOT.gStyle.SetFrameBorderMode(0)\n c.SetRightMargin(0.15);\n c.SetTopMargin(0.15);\n \n# r.correlationHist(h).Draw('colz')\n c.Update()\n c.SaveAs(plotdir+h+'_CorrelationHist_SB_combine_Cov.png')\n \n h_chargeflip = ROOT.TH2F(h+\"_CFRate\",\";P_{T}[GeV] ; |\\eta|};\",pt_bins,pt_region,eta_bins,eta_region)\n\n result = [[0. for j in range(eta_bins)] for i in range(pt_bins)]\n error = [[0. for j in range(eta_bins)] for i in range(pt_bins)]\n\n for i in range(pt_bins):\n for j in range(eta_bins):\n result = ROOT.double(0.)\n error = ROOT.double(0.)\n gMinuit.GetParameter(i*eta_bins+j,result,error)\n P_fit[h][i][j] = result\n h_chargeflip.SetBinContent(i+1,j+1,result)\n h_chargeflip.SetBinError(i+1,j+1,error)\n if h=='data':\n h_data = h_chargeflip.Clone()\n else:\n h_MC = h_chargeflip.Clone()\n c.SetLogx()\n c.SetLogz()\n h_chargeflip.Draw('COLZTEXT e')\n c.Update()\n c.SaveAs(plotdir+h+'_CFRate_MLE_SB_'+tag+'_Cov.png')\n c.SaveAs(plotdir+h+'_CFRate_MLE_SB_'+tag+'_Cov.pdf')\n\nFout = ROOT.TFile.Open(\"ChargeFlipProbability_2017_MLE.root\",\"Recreate\")\nh_data.Write()\nh_MC.Write()\nFout.Close()\n\nc.SetLogz(0) \nh_SF = h_data.Clone()\nh_SF.Divide(h_SF,h_MC)\nh_SF.Draw('COLZTEXT e')\nc.Update()\nc.SaveAs(plotdir+'CFRate_MLE_MDRatio_SB_'+tag+'_Cov.png')\nc.SaveAs(plotdir+'CFRate_MLE_MDRatio_SB_'+tag+'_Cov.pdf')\n\n\nfor i in range(pt_bins):\n for j in range(eta_bins):\n SF[i][j] = P_fit['data'][i][j]/P_fit['MC'][i][j]\n\nprint(P_fit['MC'])\nprint(SF)\n\ngenfile = os.path.join(workdir+\"/../analysis_2017_chargeflip_genmatching/genCFrate.root\")\nfin = ROOT.TFile.Open(genfile)\nh_gen = fin.Get(\"genCFRate\")\nh_MCvgen = h_gen.Clone()\nh_MCvgen.Divide(h_MCvgen,h_MC)\nh_MCvgen.Draw('COLZTEXT e')\nc.Update()\nc.SaveAs(plotdir+'CFRate_MLE_genvMC_'+tag+'_Cov.png')\nfin.Close()\n","sub_path":"TopAnalysis/ChargeFlipStudy/ChargeFlipRate.py","file_name":"ChargeFlipRate.py","file_ext":"py","file_size_in_byte":12754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"446913495","text":" # -*- coding: utf-8 -*-\nimport sys\nimport math\nimport time\nimport mymodule\nfrom tkinter import *\n\ndef read_tsp(filename):\n tsp=mymodule.smart.produce(filename)\n dist_x=tsp[0]\n dist_y=tsp[1]\n N=len(dist_x)\n buff=[]\n for i in range(N):\n buff.append((dist_x[i],dist_y[i]))\n return buff\n\n# 距離の計算\ndef distance(p1, p2):\n dx = p1[0] - p2[0]\n dy = p1[1] - p2[1]\n return math.sqrt(dx * dx + dy * dy)\n\n# 経路の距離を求める\ndef path_length(path):\n global distance_table\n n = 0\n i = 1\n for i in range(1, len(path)):\n n += distance(path[i - 1], path[i])\n n += distance(path[0], path[-1])\n return n\n\n# 分割する方向を決定する\ndef divide_direction(buff):\n x1 = min(map(lambda x: x[0], buff))\n y1 = min(map(lambda x: x[1], buff))\n x2 = max(map(lambda x: x[0], buff))\n y2 = max(map(lambda x: x[1], buff))\n return x2 - x1 > y2 - y1\n\n# 分割する\ndef divide(buff, axis):\n print (len(buff))\n buff.sort(key=lambda x:x[axis])\n n = len(buff) // 2\n buff1 = buff[0:(n+1)]\n buff2 = buff[n:]\n return buff[n], buff1, buff2\n\n# 差分を計算する\ndef differ(p, c, q):\n return distance(p, c) + distance(c, q) - distance(p, q)\n\n# 共有点を探す\ndef search(x, buff):\n for i in range(len(buff)):\n if buff[i] == x:\n if i == 0: return len(buff) - 1, i, i + 1\n if i == len(buff) - 1: return i - 1, i, 0\n return i - 1, i, i + 1\n\n# 挿入するための新しい経路を作る\ndef make_new_path(buff, c, succ):\n path = []\n i = c + succ\n while True:\n if i < 0: i = len(buff) - 1\n elif i >= len(buff): i = 0\n if i == c: break\n path.append(buff[i])\n i += succ\n return path\n\n# 併合する\n# buff1 = [a, b, c, d, e]\n# buff2 = [f, g, c, h, i]\n# (1) b - g => [a, b, g, f, i, h, c, d, e]\n# (2) d - h => [a, b, c, g, f, i, h, d, e]\n# (3) b - h => [a, b, h, i, f. g. c, d, e]\n# (4) d - g => [a, b. c. h, i, f, g, d, e]\ndef merge(buff1, buff2, p):\n #共有ポイントを探す\n p1, i1, n1 = search(p, buff1)\n p2, i2, n2 = search(p, buff2)\n # 差分を計算\n d1 = differ(buff1[p1], p, buff2[p2])\n d2 = differ(buff1[n1], p, buff2[n2])\n d3 = differ(buff1[p1], p, buff2[n2])\n d4 = differ(buff1[n1], p, buff2[p2])\n # 差分が一番大きいものを選択\n d = max(d1, d2, d3, d4)\n if d1 == d:\n # (1)\n buff1[i1:i1] = make_new_path(buff2, i2, -1)\n elif d2 == d:\n # (2)\n buff1[n1:n1] = make_new_path(buff2, i2, -1)\n elif d3 == d:\n # (3)\n buff1[i1:i1] = make_new_path(buff2, i2, 1)\n else:\n # (4)\n buff1[n1:n1] = make_new_path(buff2, i2, 1)\n return buff1\n\n# 分割統治法による解法\ndef divide_merge(buff):\n if len(buff) < 3:\n # print buff\n return buff\n else:\n if divide_direction(buff):\n p, b1, b2 = divide(buff, 0)\n else:\n p, b1, b2 = divide(buff, 1)\n b3 = divide_merge(b1)\n b4 = divide_merge(b2)\n return merge(b3, b4, p)\n\n\"\"\"\n# テスト\ndef divide_test(buff):\n if len(buff) < 26:\n draw_path(buff)\n else:\n if divide_direction(buff): #縦が長いときx座標を基準にソー\n p, b1, b2 = divide(buff, 0)\n else: #横が長いときy座標を基準にソート\n p, b1, b2 = divide(buff, 1)\n divide_test(b1)\n divide_test(b2)\n\"\"\"\n#経路の表示\ndef draw_path(path):\n x0, y0 = path[0][0]*a , path[0][1]*b\n for i in range(1, len(path)):\n x1, y1 = path[i][0]*a ,path[i][1]*b\n c0.create_line(x0, y0, x1, y1)\n x0, y0 = x1, y1\n c0.create_line(x0, y0, path[0][0]*a, path[0][1]*b)\n for x, y in path:\n c0.create_oval(x*a- 4 ,y*b- 4, x*a + 4, y*b + 4, fill = \"green\")\n\npoint_table = read_tsp(\"tsp/eil51.tsp\")\npath= divide_merge(point_table)\nprint(path_length(path))\n\ne = time.clock()\nmax_x = 800\nmax_y = 600\na= max_x // (max(map(lambda x: x[0], point_table)) +10)\nb= max_y // (max(map(lambda x: x[1], point_table)) +10)\n\nroot = Tk()\nc0 = Canvas(root, width = max_x, height = max_y, bg = \"white\")\nc0.pack()\n\ndraw_path(path)\n\nroot.mainloop()\n","sub_path":"aco/material/divide.py","file_name":"divide.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"351385879","text":"from invoke import task\nfrom os.path import join\nfrom tasks.lammps.data import upload as lammps_data_upload\nfrom tasks.util.env import (\n KERNELS_FAASM_FUNCS,\n KERNELS_FAASM_USER,\n KERNELS_WASM_DIR,\n LAMMPS_DOCKER_WASM,\n LAMMPS_FAASM_USER,\n LAMMPS_FAASM_FUNC,\n)\nfrom tasks.util.upload import upload_wasm\n\n\n@task()\ndef upload(ctx):\n \"\"\"\n Upload the MPI functions to Granny\n \"\"\"\n wasm_file_details = [\n {\n \"wasm_file\": LAMMPS_DOCKER_WASM,\n \"wasm_user\": LAMMPS_FAASM_USER,\n \"wasm_function\": LAMMPS_FAASM_FUNC,\n \"copies\": 1,\n },\n ]\n\n for kernel in KERNELS_FAASM_FUNCS:\n wasm_file_details.append(\n {\n \"wasm_file\": join(\n KERNELS_WASM_DIR, \"mpi_{}.wasm\".format(kernel)\n ),\n \"wasm_user\": KERNELS_FAASM_USER,\n \"wasm_function\": kernel,\n \"copies\": 1,\n }\n )\n\n upload_wasm(wasm_file_details)\n\n # LAMMPS also needs some extra data files\n lammps_data_upload(\n ctx, [\"compute\", \"compute-xl\", \"compute-xxl\", \"network\"]\n )\n","sub_path":"tasks/mpi/wasm.py","file_name":"wasm.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"502729392","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 15 14:49:33 2017\n\n@author: nb\n\"\"\"\n\nimport unittest\n\n\nimport numpy as np\n\nfrom .context import viroconcom\n\nfrom viroconcom.params import ConstantParam, FunctionParam\nfrom viroconcom.distributions import (WeibullDistribution, LognormalDistribution, NormalDistribution,\n KernelDensityDistribution,\n MultivariateDistribution)\n\nclass MultivariateDistributionTest(unittest.TestCase):\n \"\"\"\n Create a example MultivariateDistribution\n \"\"\"\n\n #define dependency tuple\n dep1 = (None, 0, None)\n dep2 = (0, None, 0)\n\n #define parameters\n shape = ConstantParam(1.471)\n loc = ConstantParam(0.8888)\n scale = ConstantParam(2.776)\n par1 = (shape, loc, scale)\n\n shape = FunctionParam(0.0400, 0.1748, -0.2243, \"f2\")\n loc = None\n scale = FunctionParam(0.1, 1.489, 0.1901, \"f1\")\n par2 = (shape, loc, scale)\n\n del shape, loc, scale\n\n #create distributions\n dist1 = WeibullDistribution(*par1)\n dist2 = LognormalDistribution(*par2)\n\n distributions = [dist1, dist2]\n dependencies = [dep1, dep2]\n\n\n def test_add_distribution_err_msg(self):\n \"\"\"\n tests if the right exception is raised when distribution1 has a\n dependency\n \"\"\"\n\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, self.dependencies)\n\n\n def test_add_distribution_iter(self):\n \"\"\"\n tests if an exception is raised by the function add_distribution when\n distributions isn't iterable but dependencies is and the other way around\n \"\"\"\n\n distributions = 1\n with self.assertRaises(ValueError):\n MultivariateDistribution(distributions, self.dependencies)\n dependencies = 0\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n def test_add_distribution_length(self):\n \"\"\"\n tests if an exception is raised when distributions and dependencies\n are of unequal length\n \"\"\"\n\n dep3 = (0, None, None)\n dependencies = [self.dep1, self.dep2, dep3]\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n def test_add_distribution_dependencies_length(self):\n \"\"\"\n tests if an exception is raised when a tuple in dependencies\n has not length 3\n \"\"\"\n\n dep1 = (None, None)\n dependencies = [dep1, self.dep2]\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n def test_add_distribution_dependencies_value(self):\n \"\"\"\n tests if an exception is raised when dependencies has an invalid value\n \"\"\"\n\n dep1 = (-3, None, None)\n dependencies = [dep1, self.dep2]\n with self.assertRaises(ValueError):\n MultivariateDistribution(self.distributions, dependencies)\n\n\n\n def test_add_distribution_not_iterable(self):\n \"\"\"\n tests the function when both distributions and dependencies\n are not iterable\n \"\"\"\n\n distributions = 1\n dependencies = 2\n with self.assertRaises(ValueError):\n MultivariateDistribution(distributions, dependencies)\n\n\n\nclass ParametricDistributionTest(unittest.TestCase):\n\n def test_distribution_shape_None(self):\n \"\"\"\n tests if shape is set to default when it has value 'None'\n \"\"\"\n\n #define parameters\n shape = None\n loc = ConstantParam(0.8888)\n scale = ConstantParam(2.776)\n par1 = (shape, loc, scale)\n rv_values = [0.8, 1, 8]\n dependencies = (0, 1, 1)\n\n dist = NormalDistribution(*par1)\n shape_test = dist._get_parameter_values(rv_values, dependencies)[0]\n self.assertEqual(shape_test, 1)\n\n\n def test_distribution_loc_None(self):\n \"\"\"\n tests if loc is set to default when it has value 'None'\n \"\"\"\n\n #define parameters\n shape = ConstantParam(0.8888)\n loc = None\n scale = ConstantParam(2.776)\n par1 = (shape, loc, scale)\n rv_values = [0.8, 1, 8]\n dependencies = (0, 1, 1)\n\n dist = WeibullDistribution(*par1)\n loc_test = dist._get_parameter_values(rv_values, dependencies)[1]\n self.assertEqual(loc_test, 0)\n\n\n def test_distribution_loc_scale(self):\n \"\"\"\n tests if scale is set to default when it has value 'None'\n \"\"\"\n\n #define parameters\n shape = ConstantParam(0.8888)\n loc = ConstantParam(2.776)\n scale = None\n par1 = (shape, loc, scale)\n rv_values = [0.8, 1, 8]\n dependencies = (0, 1, 1)\n\n dist = NormalDistribution(*par1)\n scale_test = dist._get_parameter_values(rv_values, dependencies)[2]\n self.assertEqual(scale_test, 1)\n\n\n def test_check_parameter_value(self):\n \"\"\"\n tests if the right exception is raised when the given parameters are\n not in the valid range of numbers\n \"\"\"\n\n shape = None\n loc = ConstantParam(0.8888)\n scale = ConstantParam(-2.776)\n par1 = (shape, loc, scale)\n\n dist = WeibullDistribution(*par1)\n\n with self.assertRaises(ValueError):\n dist._check_parameter_value(2, -2.776)\n with self.assertRaises(ValueError):\n dist._check_parameter_value(2, np.inf)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/test_distributions.py","file_name":"test_distributions.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"454089451","text":"import inspect\n\nfrom pepys_import.core.store import sqlite_db\n\n\ndef row_to_dict(table_object, data_store):\n \"\"\"Converts all entities of a table into a dict of {column_name: value}s.\n\n :param table_object: A table object\n :type table_object: sqlalchemy.ext.declarative.DeclarativeMeta\n :param data_store: A :class:`DataStore` object\n :type data_store: DataStore\n :return: Returns a dictionary with values\n :rtype: Dict\n \"\"\"\n with data_store.session_scope():\n values = data_store.session.query(table_object).all()\n objects = list()\n for row in values:\n d = {column.name: getattr(row, column.name) for column in row.__table__.columns}\n objects.append(d)\n return objects\n\n\ndef find_sqlite_table_object(table_object, data_store):\n \"\"\"Finds and returns a SQLite Base class which will be used to create and insert values.\n\n :param table_object: A table object\n :type table_object: sqlalchemy.ext.declarative.DeclarativeMeta\n :param data_store: A :class:`DataStore` object\n :type data_store: DataStore\n :return: Returns a table object\n :rtype: sqlalchemy.ext.declarative.DeclarativeMeta\n \"\"\"\n if data_store.db_type == \"postgres\":\n for name, obj in inspect.getmembers(sqlite_db):\n if inspect.isclass(obj) and name == table_object.__name__:\n return obj\n else:\n return table_object\n\n\ndef export_reference_tables(source_store, destination_store, table_objects):\n \"\"\"Copies table objects from :code:`source_store` to :code:`destination_store`.\n\n :param source_store: A :class:`DataStore` object to fetch objects\n :type source_store: DataStore\n :param destination_store: A :class:`DataStore` object to copy the objects from source_store\n :type destination_store: DataStore\n :param table_objects: A list of table objects\n :type table_objects: List\n :return:\n \"\"\"\n for table_object in table_objects:\n dict_values = row_to_dict(table_object, source_store)\n object_ = find_sqlite_table_object(table_object, source_store)\n with destination_store.session_scope():\n destination_store.session.bulk_insert_mappings(object_, dict_values)\n\n\ndef export_metadata_tables(source_store, destination_store, privacy_ids):\n \"\"\"Copies :code:`Platform`, :code:`Sensor` and :code:`Synonym` objects from\n :code:`source_store` to :code:`destination_store`.\n\n :param source_store: A :class:`DataStore` object to fetch objects\n :type source_store: DataStore\n :param destination_store: A :class:`DataStore` object to copy the objects from source_store\n :type destination_store: DataStore\n :param privacy_ids: A list of Privacy ID's which is used to filter Platform and Sensor objects\n :type privacy_ids: List\n :return:\n \"\"\"\n for table_object in [\n source_store.db_classes.Platform,\n source_store.db_classes.Sensor,\n source_store.db_classes.Synonym,\n ]:\n with source_store.session_scope():\n dict_values = list()\n if table_object.__name__ == \"Platform\":\n values = (\n source_store.session.query(table_object)\n .filter(table_object.privacy_id.in_(privacy_ids))\n .all()\n )\n platform_ids = [row.platform_id for row in values]\n elif table_object.__name__ == \"Sensor\":\n values = (\n source_store.session.query(table_object)\n .filter(table_object.host.in_(platform_ids))\n .filter(table_object.privacy_id.in_(privacy_ids))\n .all()\n )\n sensor_ids = [row.sensor_id for row in values]\n else:\n all_ids = list()\n all_ids.extend(platform_ids)\n all_ids.extend(sensor_ids)\n values = (\n source_store.session.query(source_store.db_classes.Synonym)\n .filter(source_store.db_classes.Synonym.entity.in_(all_ids))\n .all()\n )\n for row in values:\n d = {column.name: getattr(row, column.name) for column in row.__table__.columns}\n dict_values.append(d)\n\n object_ = find_sqlite_table_object(table_object, source_store)\n with destination_store.session_scope():\n destination_store.session.bulk_insert_mappings(object_, dict_values)\n","sub_path":"pepys_admin/snapshot_helpers.py","file_name":"snapshot_helpers.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"216571109","text":"import os\nimport sys\n\ndef computeTrueCase(filename, output_file='output_files'):\n log = ''\n try:\n print ('Converting to PDF...')\n\n if not os.path.exists(output_file):\n os.makedirs(output_file)\n\n log = os.popen('pdflatex --output-directory={0} {1}'.format(output_file, filename)).read()\n\n # Uncomment to open pdf after build completes\n # os.popen('open {0}'.format('{0}/{1}pdf'.format(output_file, filename[:-3]))).read()\n\n print(log)\n print ('Done!')\n except:\n print(log)\n print('Ooops! Something went wrong. Does the folder name you provided exist?')\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Please provide filename and output directory')\n print('i.e. python toPDF.py HW0.tex')\n exit()\n if len(sys.argv) > 2:\n print('Too many arguments provided')\n exit()\n print(os.getcwd())\n if not os.path.exists(sys.argv[1]):\n print('Tex file you provided does not exist.')\n exit()\n\n computeTrueCase(sys.argv[1])\n","sub_path":"WrittenHW/buildPDF.py","file_name":"buildPDF.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"416291066","text":"from flask import Flask, render_template, session, redirect, url_for, flash, request\nfrom flask_bootstrap import Bootstrap\nfrom flask_moment import Moment\nfrom flask_wtf import FlaskForm\nfrom wtforms import TextField, IntegerField, TextAreaField\nfrom wtforms import SubmitField, RadioField, SelectField\nfrom wtforms import validators, ValidationError\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired\nfrom flask_script import Manager\nfrom frame import Frame\n\nfrom threading import Thread, Lock\nfrom hksSer import serThread, serVar\nimport time\n\nmySer = serThread()\nmySerVar = serVar\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hard to guess string'\n\nbootstrap = Bootstrap(app)\nmoment = Moment(app)\nmanager = Manager(app)\n\nclass ControlForm(FlaskForm):\n gid = IntegerField(\"Group Id: \",[validators.Required(\"Please enter your name.\")])\n pid = IntegerField(\"Private Id: \",[validators.Required(\"Please enter your name.\")])\n level = IntegerField(\"Level: \",[validators.Required(\"Please enter your name.\")])\n sub = RadioField('Command', choices=[('103','Control'),\n ('104','NewSet'), ('109','Alternative'), ('110','Status'), ('101','Power')])\n submit = SubmitField(\"Send\")\n\nclass NameForm(FlaskForm):\n name = StringField('What is your name?', validators=[DataRequired()])\n submit = SubmitField('Submit')\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n form = NameForm()\n if form.validate_on_submit():\n old_name = session.get('name')\n if old_name is not None and old_name != form.name.data:\n flash('Looks like you have changed your name!')\n session['name'] = form.name.data\n return redirect(url_for('index'))\n return render_template('index.html', form=form, name=session.get('name'))\n\n@app.route('/test', methods=['GET', 'POST'])\ndef test():\n form = ControlForm()\n if form.validate_on_submit():\n print('validate_on_submit')\n myFrame = Frame()\n myFrame.setFrame()\n print(myFrame.getFrame())\n print('bsl frame test')\n return render_template('control.html', form=form)\n\nclass testThread(Thread):\n def __init__(self):\n print('Start testThread')\n Thread.__init__(self)\n def run(self):\n while True:\n time.sleep(1) #for thread, very important\n if mySer.myVar.readFlag:\n mySer.myVar.readFlag = False\n print('var:{}'.format(mySerVar.readFlag))\n mySer.send(mySer.readStr)\n print('self.myVar.readFlag')\n print('End of testThread')\n\n\ntestThreadFirstFlag = True\n@app.route('/new', methods=['GET', 'POST'])\ndef new():\n form = ControlForm()\n global testThreadFirstFlag\n if testThreadFirstFlag:\n print('Generate testThread')\n testThreadFirstFlag = False\n myThread = testThread()\n myThread.start()\n return render_template('control.html', form=form)\n\n@app.route('/stop', methods=['GET', 'POST'])\ndef stop():\n form = ControlForm()\n if mySer.getSerAlive():\n mySer.send('Quit Serial')\n else:\n print('at start Finished Serial')\n return render_template('control.html', form=form)\n\n@app.route('/start', methods=['GET', 'POST'])\ndef startSer():\n form = ControlForm()\n if mySer.serFirstFlag:\n mySer.serFirstFlag = False\n mySer.start()\n print('Now start my Serial')\n time.sleep(1)\n return render_template('control.html', form=form)\n\n@app.route('/', methods=['GET', 'POST'])\ndef control():\n startSer()\n form = ControlForm()\n if request.method == 'POST':\n if form.validate() == False:\n flash('All fields are required.')\n print('form.validate() == False:')\n return render_template('control.html', form=form)\n else:\n myFrame = Frame()\n gid = request.form['gid']\n pid = request.form['pid']\n level = request.form['level']\n sub = request.form['sub']\n print('gid:{}, pid:{}, level:{}, sub:{}'.format(gid, pid, level, sub))\n myFrame.setGid(int(gid)); myFrame.setPid(int(pid)); myFrame.setLevel(int(level));\n myFrame.setSub(int(sub))\n myFrame.setFrame()\n mySer.send(myFrame.getFrame())\n return render_template('control.html', form=form)\n\n elif request.method == 'GET':\n print('request.method == GET ')\n return render_template('control.html', form=form)\n\nif __name__ == '__main__':\n app.run(debug=True)\n print('Now Run')\n # manager.run()\n# python3 hello.py runserver --host 0.0.0.0\n","sub_path":"project/serverTest/bsl.py","file_name":"bsl.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"78992798","text":"# Copyright 2018 luozhouyang\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport os\n\nimport tensorflow as tf\n\nfrom naivenmt.utils import get_dict_from_collection\nfrom naivenmt.utils import get_predictions\n\n\nclass SaveEvaluationPredictionsHook(tf.train.SessionRunHook):\n \"\"\"Do evaluation and save prediction results to file.\"\"\"\n\n def __init__(self,\n out_dir,\n eos=\"\",\n subword_option=\"\",\n post_evaluation_fn=None):\n \"\"\"Init.\n\n Args:\n out_dir: model's dir\n eos: eos of params\n subword_option: subword options of params\n post_evaluation_fn: a callback fn with signature (global_steps, predictions_file),\n called after saving predictions\n \"\"\"\n self.eos = eos\n self.subword_option = subword_option\n self.output_file = os.path.join(out_dir, \"output_dev\")\n self.post_evaluation_fn = post_evaluation_fn\n self.predictions = None\n self.global_steps = None\n\n def begin(self):\n self.predictions = get_dict_from_collection(\"predictions\")\n self.global_steps = tf.train.get_global_step()\n\n def before_run(self, run_context):\n if not self.predictions:\n raise ValueError(\"Model does not define predictions.\")\n if not self.global_steps:\n raise ValueError(\"Not created global steps.\")\n return tf.train.SessionRunArgs([self.predictions, self.global_steps])\n\n def after_run(self,\n run_context, # pylint: disable=unused-argument\n run_values):\n predictions, self.global_steps = run_values.results\n self.output_file = self.output_file + \".\" + self.global_steps\n predictions = get_predictions(predictions, self.eos, self.subword_option)\n\n with open(self.output_file, mode=\"a\", encoding=\"utf8\") as f:\n if isinstance(predictions, str):\n f.write(predictions + \"\\n\")\n elif isinstance(predictions, list):\n for p in predictions:\n f.write(p + \"\\n\")\n\n def end(self, session):\n tf.logging.info(\"Evaluation predictions saved to %s\" % self.output_file)\n if self.post_evaluation_fn:\n self.post_evaluation_fn(self.global_steps, self.output_file)\n","sub_path":"naivenmt/hooks/eval_hooks.py","file_name":"eval_hooks.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"646413931","text":"#!/usr/bin/env python\n\nfrom os.path import basename\n\nimport six\n\nfrom .core import Multipart, Field\n\n\ndef encode(fields):\n field_list = []\n\n for name, value in six.iteritems(fields):\n explicit_filename = ''\n if isinstance(value, (tuple, list)):\n value, explicit_filename = value\n\n if hasattr(value, 'read'):\n # Quacks like a file\n field_list.append(\n Field(name, fileobj=value, filename=(explicit_filename or basename(value.name)))\n )\n\n else:\n field_list.append(Field(name, value))\n\n return Multipart(field_list)\n","sub_path":"multipart/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"608147197","text":"#! /usr/bin/env python3\n\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\n\ndef getRunNumber(inputstring: str):\n delim = inputstring.find(\"_\")\n if delim < 0:\n return -1\n runnostring = inputstring[:delim]\n if runnostring.isdigit():\n return int(runnostring)\n return -1\n\nif __name__ == \"__main__\":\n scriptdir = os.path.dirname(os.path.abspath(sys.argv[0]))\n submitter = os.path.join(scriptdir, \"submitMergeMCDatasets.py\")\n parser = argparse.ArgumentParser(\"submitMergeSamples.py\", description=\"Launch merging of single dataset merging\")\n parser.add_argument(\"inputdir\", metavar=\"INPUTDIR\", type=str, help=\"Input directory\")\n parser.add_argument(\"-f\", \"--file\", metavar=\"FILE\", type=str, default=\"AnalysisResults.root\", help=\"\")\n parser.add_argument(\"-p\", \"--partition\", metavar=\"PARTITION\", type=str, default=\"vip\", help=\"Partition of the 587 cluster\")\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", help=\"Debug mode\")\n args = parser.parse_args()\n\n loglevel = logging.INFO\n if args.debug:\n loglevel = logging.DEBUG\n logging.basicConfig(format=\"%(levelname)s: %(message)s\", level=loglevel)\n\n samples = [x for x in os.listdir(os.path.abspath(args.inputdir)) if \"LHC\" in x]\n if not len(samples):\n # check if runwise\n samples = [x for x in os.listdir(os.path.abspath(args.inputdir)) if x.isdigit()]\n for sample in samples:\n logging.info(\"Submitting %s ...\", sample)\n fullsamplepath = os.path.join(args.inputdir, sample)\n submitcmd = \"{EXE} {SAMPLEDIR} -f {FILE} -p {PARTITION}\".format(EXE=submitter, SAMPLEDIR=fullsamplepath, FILE=args.file, PARTITION=args.partition)\n subprocess.call(submitcmd, shell=True)","sub_path":"merge/submitMergeSamplesDataset.py","file_name":"submitMergeSamplesDataset.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"191870468","text":"\"\"\"\nURLconf for registration and activation, based on django-registration's\ndefault backend.\n\n\"\"\"\n\nfrom django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\n\nfrom corehq.apps.registration.user_registration_backend import activate_by_form\n\nurlpatterns = patterns('',\n url(r'^register/closed/$',\n direct_to_template,\n { 'template': 'registration/backend/registration_closed.html' },\n name='registration_disallowed'), \n\n # Activation keys get matched by \\w+ instead of the more specific\n # [a-fA-F0-9]{40} because a bad activation key should still get to the view;\n # that way it can return a sensible \"invalid key\" message instead of a\n # confusing 404.\n # Because our main activation workflow relies on the user adding new data\n # at activation time, we can't use the default 'activate.' Had to rewrite it. \n url(r'^activate/user_inputs_data/(?P\\w+)/$',\n activate_by_form,\n { 'backend': 'corehq.apps.registration.user_registration_backend.UserRegistersSelfBackend' },\n name='registration_activate_user_inputs_data'), \n \n url(r'^activate/complete(?:/(?P\\w+))?(?:/(?P\\w+))?/$',\n direct_to_template,\n { 'template': 'registration/backend/activation_complete.html' },\n name='registration_activation_complete') \n )\n","sub_path":"corehq/apps/registration/user_registration_backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"52162049","text":"\nimport speech_recognition #Speech to text chuyển giọng nói thành văn bản Tiếng việt\nfrom gtts import gTTS #Chuyển văn bản thành giọng nói Tiếng Việt\nimport os #Thực thi câu lệnh trong CMD\nfrom playsound import playsound #Chạy âm thanh mp3\nimport datetime #Lấy ngày hiện tại\nfrom selenium import webdriver #Mô phỏng thao tác click chuột trên Browser\nfrom time import sleep #Nghỉ\nfrom pynput.keyboard import Key, Controller #Tự động sử dụng bàn phím\nfrom selenium.webdriver.common.keys import Keys\nimport xlrd\nimport xlwt\n\nkeyboard = Controller() #Khởi tạo bàn phím ảo\nbot_brain= \"\" #Khởi tạo biến suy nghĩ của robot\nbot_ear = speech_recognition.Recognizer() #Khởi tạo biến bot_ear bằng Giọng nói người thật truyền vào chuyển thành văn bản dưới dạng chuỗi\nfile_location = \"output.xls\"\nwb = xlrd.open_workbook(file_location)\nsheet1 = wb.sheet_by_index(0)\nhang = sheet1.nrows\ncot = sheet1.ncols\nprint('số hàng trong Excel:')\nprint(sheet1.nrows)\nprint('số cột trong Excel:')\nprint(sheet1.ncols)\ni=0\ndem=0\nworkbook = xlrd.open_workbook('driendlist.xlsx')\nsheet = workbook.sheet_by_index(0)\ndata = [sheet.cell_value(0, 1) for col in range(sheet.ncols)]\nworkbook = xlwt.Workbook()\nsheet = workbook.add_sheet('Friend')\nmangtim = []\nlinktim = []\n\nwhile True: #Biến vô tận\n with speech_recognition.Microphone() as mic: #Chờ đợi sử dụng Mic để chuyển thành văn bản\n print(\"\\nSiri: I'm listening\")\n #audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration= 5) #Sau khi nghe từ Mic, nhận biến audio là sound\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio,language='vi-VN').upper() #truyền biến audio lên API GG, nhận về chuỗi kí tự theo giọng nói\n print(\"\\nYou: \"+you)\n except:\n you=\"\"\n print(\"\\nSiri: \"+you)\n if \"XIN CHÀO\" in you:\n bot_brain = \"Xin chào Dũng\"\n elif you == \"\":\n bot_brain =\"\"\n elif \"GIỎI\" in you:\n bot_brain =\"Cảm ơn nhé ! Đó là điều tôi nên làm\"\n elif \"BẠN CÓ THỂ GIÚP GÌ\" in you:\n bot_brain = \"Tôi có thể giúp bạn tìm kiếm thông tin, chơi nhạc, chụp ảnh\"\n elif \"GỌI\" in you:\n bot_brain = \"Gọi cho ai\"\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n with speech_recognition.Microphone() as mic:\n print(\"\\nSiri: I'm listening\")\n # audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration=5)\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio, language='vi-VN').upper()\n print(\"\\nYou: \" + you)\n except:\n you = \"\"\n print(\"\\nSiri: \" + you)\n if you == \"\":\n bot_brain = \"Google đây, bạn tự tìm lấy nhé\"\n os.system(\"start www.google.com\")\n # chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument(\"--incognito\")\n # browser = webdriver.Chrome(chrome_options=chrome_options)\n # browser.get(\"https://www.facebook.com/videocall/incall/?peer_id=100006131910859\")\n # sleep(1)\n # mail = browser.find_element_by_id('email')\n # mail.send_keys('phantridungdz')\n # password = browser.find_element_by_id('pass')\n # password.send_keys('buonthicukhocdi123')\n # password.send_keys(Keys.ENTER)\n # sleep(2)\n # browser.get(\"https://www.facebook.com/messages/t/100006131910859\")\n # doit = browser.find_element_by_xpath(\n # '/html/body/div[1]/div[1]/div[1]/div/div/div/div[2]/span/div[1]/ul/li[1]/a')\n # doit.click()\n else:\n tencantim = you\n while i < hang:\n nickname = sheet1.cell_value(i, 0).upper()\n link = sheet1.cell_value(i, 1)\n b = nickname.split()\n count = len(b)\n if tencantim in b:\n d = ' '.join(b)\n link1 = link.lstrip('https://www.faceboo')\n link2 = link1.lstrip('k.com')\n link3 = link2.lstrip('/')\n kiemtra = link3.startswith('profile.php?id=')\n if kiemtra == True:\n link4 = link3.lstrip('profile.php?id=')\n mangtim.append(d)\n linktim.append(link4)\n i += 1\n # soketqua = len(mangtim)\n # bot_brain = \"có \"+ str(soketqua) + \" \"+ tencantim + \" trong danh sách bạn bè, bạn muốn gọi \" + tencantim +\" mấy?\"\n # tts = gTTS(text=bot_brain, lang='vi')\n # tts.save(\"Siri.mp3\")\n # playsound(\"Siri.mp3\")\n # os.remove(\"Siri.mp3\")\n\n bot_brain = \"đang gọi \"+ mangtim[1]\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n\n os.system(\"start www.facebook.com/videocall/incall/?peer_id=\"+linktim[1])\n sleep(4)\n keyboard.press(Key.tab)\n keyboard.release(Key.tab)\n keyboard.press(Key.tab)\n keyboard.release(Key.tab)\n keyboard.press(Key.enter)\n keyboard.release(Key.enter)\n\n\n elif \"chụp ảnh\"in you:\n bot_brain =\"Cười lên nào !\"\n os.system(\"start microsoft.windows.camera:\")\n sleep(2)\n keyboard.press(Key.enter)\n keyboard.release(Key.enter)\n bot_brain = \"Xong rồi đó, một bức ảnh tuyệt đẹp!\"\n elif \"thời tiết\" in you:\n bot_brain = \" Hôm nay trời nhiều mây\"\n elif \"Facebook\" in you:\n os.system(\"start www.facebook.com\")\n bot_brain = \"Em mở facebook cho anh rồi nhé\"\n elif \"Youtube\" in you:\n os.system(\"start www.youtube.com\")\n bot_brain = \"Em mở youtube cho anh rồi nhé\"\n elif \"Google\" in you:\n os.system(\"start www.google.com\")\n bot_brain = \"Em mở Google cho anh rồi nhé\"\n\n elif \"ngày\" in you:\n bot_brain = datetime.datetime.now().strftime(\"%A\") #=Monday\n elif \"Mở nhạc\" in you:\n bot_brain = \"Bạn muốn nghe bài gì ?\"\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n with speech_recognition.Microphone() as mic:\n print(\"\\nSiri: I'm listening\")\n # audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration=5)\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio, language='vi-VN')\n print(\"\\nYou: \" + you)\n except:\n you = \"\"\n print(\"\\nSiri: \" + you)\n if you == \"\":\n bot_brain = \"Google đây, bạn tự tìm lấy nhé\"\n os.system(\"start www.google.com\")\n else:\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(\"--incognito\")\n browser = webdriver.Chrome(chrome_options=chrome_options)\n browser.get(\"http://youtube.com/\")\n doit = browser.find_element_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input')\n doit.send_keys(you)\n doit = browser.find_element_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/button')\n doit.click()\n sleep(3)\n doit = browser.find_element_by_xpath('/html/body/ytd-app/div/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-video-renderer[1]/div[1]/ytd-thumbnail/a/yt-img-shadow')\n doit.click()\n bot_brain = \"Chúc bạn nghe nhạc vui vẻ\"\n elif \"tìm\" in you:\n bot_brain = \"Bạn muốn tìm gì ?\"\n tts = gTTS(text=bot_brain, lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n os.remove(\"Siri.mp3\")\n with speech_recognition.Microphone() as mic:\n print(\"\\nSiri: I'm listening\")\n # audio = bot_ear.listen(mic)\n audio = bot_ear.record(mic, duration=5)\n print(\"\\nSiri: ....\")\n try:\n you = bot_ear.recognize_google(audio, language='vi-VN')\n print(\"\\nYou: \" + you)\n except:\n you = \"\"\n print(\"\\nSiri: \" + you)\n if you == \"\":\n bot_brain = \"Google đây, bạn tự tìm lấy nhé\"\n else:\n os.system(\"start www.google.com/search?q=\"+you.replace(' ','+'))\n bot_brain = \"Đây là kết quả tôi tìm được\"\n\n else:\n os.system(\"start www.google.com/search?q=\" + you.replace(' ', '+'))\n bot_brain = \"Đây là kết quả tìm kiếm trên google !\"\n print(\"\\nSiri: \" + bot_brain)\n try:\n tts = gTTS(text = bot_brain,lang='vi')\n tts.save(\"Siri.mp3\")\n playsound(\"Siri.mp3\")\n\n except:\n bot_brain=\"\"","sub_path":"Nghetiengviet.py","file_name":"Nghetiengviet.py","file_ext":"py","file_size_in_byte":9246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"18891095","text":"#!/usr/bin/env python3\n\"\"\" Python Flask Module \"\"\"\n\n\nfrom flask import Flask, render_template\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n \"\"\"Index page\"\"\"\n return render_template('0-index.html')\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"0x0A-i18n/0-app.py","file_name":"0-app.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"217137688","text":"import pytest\nfrom selenium import webdriver\n\n@pytest.fixture(scope=\"class\")\ndef setUp(request):\n driver = webdriver.Chrome(executable_path=\"/Users/kashirol/Downloads/chromedriver\")\n driver.get(\"https://rahulshettyacademy.com/seleniumPractise/\")\n driver.maximize_window()\n request.cls.driver = driver\n yield\n driver.close()","sub_path":"PythonTestFramework/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"402222930","text":"# -*- coding: utf-8 -*- #\n# Copyright 2019 Google LLC. All Rights Reserved.\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\"\"\"Utils for GKE Hub commands.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.util import waiter\nfrom googlecloudsdk.command_lib.container.hub import kube_util\nfrom googlecloudsdk.core import exceptions\n\n# The CustomResourceDefinition for the Membership Resource. It is created on an\n# as needed basis when registering a cluster to the hub.\nMEMBERSHIP_CRD_MANIFEST = \"\"\"\\\napiVersion: apiextensions.k8s.io/v1beta1\nkind: CustomResourceDefinition\nmetadata:\n name: memberships.hub.gke.io\nspec:\n group: hub.gke.io\n scope: Cluster\n names:\n plural: memberships\n singular: membership\n kind: Membership\n versions:\n - name: v1beta1\n served: true\n storage: true\n validation:\n openAPIV3Schema:\n required:\n - spec\n properties:\n metadata:\n type: object\n properties:\n name:\n type: string\n pattern: '^(membership|test-.*)$'\n spec:\n type: object\n properties:\n owner:\n type: object\n properties:\n id:\n type: string\n description: Membership owner ID. Should be immutable.\"\"\"\n\n# The Membership Resource that enforces cluster exclusivity. It specifies the\n# hub project that the cluster is registered to. During registration, it is used\n# to ensure a user does not register a cluster to multiple hub projects.\nMEMBERSHIP_CR_TEMPLATE = \"\"\"\\\nkind: Membership\napiVersion: hub.gke.io/v1beta1\nmetadata:\n name: membership\nspec:\n owner:\n id: projects/{project_id}\"\"\"\n\n\ndef GetMembershipCROwnerID(kube_client):\n \"\"\"Returns the project id of the hub the cluster is a member of.\n\n The Membership Custom Resource stores the project id of the hub the cluster\n is registered to in the `.spec.owner.id` field.\n\n Args:\n kube_client: A KubernetesClient.\n\n Returns:\n a string, the project id\n None, if the Membership CRD or CR do not exist on the cluster.\n\n Raises:\n exceptions.Error: if the Membership resource does not have a valid owner id\n \"\"\"\n\n owner_id = kube_client.GetMembershipOwnerID()\n if owner_id is None:\n return None\n id_prefix = 'projects/'\n if not owner_id.startswith(id_prefix):\n raise exceptions.Error(\n 'Membership .spec.owner.id is invalid: {}'.format(owner_id))\n return owner_id[len(id_prefix):]\n\n\ndef ApplyMembershipResources(kube_client, project):\n \"\"\"Creates or updates the Membership CRD and CR with the hub project id.\n\n Args:\n kube_client: A KubernetesClient.\n project: The project id of the hub the cluster is a member of.\n\n Raises:\n exceptions.Error: if the Membership CR or CRD couldn't be applied.\n \"\"\"\n\n membership_cr_manifest = MEMBERSHIP_CR_TEMPLATE.format(project_id=project)\n kube_client.ApplyMembership(MEMBERSHIP_CRD_MANIFEST, membership_cr_manifest)\n\n\ndef DeleteMembershipResources(kube_client):\n \"\"\"Deletes the Membership CRD.\n\n Due to garbage collection all Membership resources will also be deleted.\n\n Args:\n kube_client: A KubernetesClient.\n \"\"\"\n\n try:\n succeeded, error = waiter.WaitFor(\n kube_util.KubernetesPoller(),\n MembershipCRDeleteOperation(kube_client),\n 'Deleting membership CR in the cluster',\n pre_start_sleep_ms=kube_util.NAMESPACE_DELETION_INITIAL_WAIT_MS,\n max_wait_ms=kube_util.NAMESPACE_DELETION_TIMEOUT_MS,\n wait_ceiling_ms=kube_util.NAMESPACE_DELETION_MAX_POLL_INTERVAL_MS,\n sleep_ms=kube_util.NAMESPACE_DELETION_INITIAL_POLL_INTERVAL_MS)\n except waiter.TimeoutError:\n # waiter.TimeoutError assumes that the operation is a Google API\n # operation, and prints a debugging string to that effect.\n raise exceptions.Error('Timeout deleting membership CR from cluster.')\n\n if not succeeded:\n raise exceptions.Error(\n 'Could not delete membership CR from cluster. Error: {}'.format(error))\n\n\nclass MembershipCRDeleteOperation(object):\n \"\"\"An operation that waits for a membership CR to be deleted.\"\"\"\n\n def __init__(self, kube_client):\n self.kube_client = kube_client\n self.done = False\n self.succeeded = False\n self.error = None\n\n def __str__(self):\n return ''\n\n def Update(self):\n \"\"\"Updates this operation with the latest membership CR deletion status.\"\"\"\n err = self.kube_client.DeleteMembership()\n\n # The first delete request should succeed.\n if not err:\n return\n\n # If deletion is successful, the delete command will return a NotFound\n # error.\n if 'NotFound' in err:\n self.done = True\n self.succeeded = True\n else:\n self.error = err\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/container/hub/exclusivity_util.py","file_name":"exclusivity_util.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"470367116","text":"__author__ = \"Jayde Yue\"\n# Website: www.jaydeyue.com\n\n\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport threading\n\n\nclass DictWorker(threading.Thread):\n\n def __init__(self, dict, scanner, dict_number):\n threading.Thread.__init__(self)\n self.dict = dict\n self.scanner = scanner\n self.dict_number = dict_number\n\n def request_with_retrys(self, session):\n retry = Retry(\n total=self.scanner.max_retrys,\n read=self.scanner.max_retrys,\n connect=self.scanner.max_retrys,\n backoff_factor=0.3,\n status_forcelist=(500, 502, 504),\n )\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n def procese_valid_url(self, request_url, response):\n print(request_url + \": \" + str(response.status_code))\n self.scanner.dict_stats[self.dict_number] +=1\n if not self.scanner.allow_overlap:\n self.scanner.all_trys[request_url[len(self.scanner.base_url):]] = 1\n\n def run(self):\n while not self.dict.empty():\n try:\n request_url = self.scanner.base_url + self.dict.get_nowait()\n session = requests.Session()\n if self.scanner.user != '':\n session.auth = (self.scanner.user, self.scanner.pwd)\n session.headers.update({\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',\n 'Referer': self.scanner.referer,\n 'Cookie': self.scanner.cookie,\n })\n response = self.request_with_retrys(session).get(request_url, timeout=self.scanner.time_out, allow_redirects=self.scanner.allow_redirect)\n if response.status_code != 404:\n if self.scanner.allow_redirect:\n if len(response.history) > 0:\n if response.url not in self.scanner.redirect_list:\n self.scanner.redirect_list[response.url] = [request_url]\n else:\n self.scanner.redirect_list[response.url].append(request_url)\n # self.scanner.dict_stats[self.dict_number] +=1\n else:\n self.procese_valid_url(request_url, response)\n elif response.status_code != 302 and response.status_code != 301:\n self.procese_valid_url(request_url, response)\n except Exception as e:\n print(e)\n break\n","sub_path":"Scanner/DictWorker.py","file_name":"DictWorker.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"307350310","text":"# LocalDotfile\nimport os\nimport simplejson as json\nPLUGIN_LOG_TITLE = 'Local Dotfile' # Log Title\n\nVERSION_NO = '2016.04.10.1'\n\n# Delay used when requesting HTML, may be good to have to prevent being banned\n# from the site\nREQUEST_DELAY = 0\n\n\ndef Start():\n HTTP.CacheTime = CACHE_1WEEK\n HTTP.Headers['User-agent'] = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows ' \\\n 'NT 6.2; Trident/4.0; SLCC2; .NET ' \\\n 'CLR 2.0.50727; .NET CLR 3.5.30729; ' \\\n '.NET CLR 3.0.30729; Media Center PC 6.0)'\n\n\nclass LocalDotfile(Agent.Movies):\n name = 'Local Dotfile'\n languages = [Locale.Language.NoLanguage, Locale.Language.English]\n primary_provider = False\n contributes_to = ['com.plexapp.agents.cockporn']\n\n def Log(self, message, *args):\n if Prefs['debug']:\n Log(PLUGIN_LOG_TITLE + ' - ' + message, *args)\n\n def search(self, results, media, lang, manual):\n self.Log('------------------------------------------------------------'\n '-----------')\n self.Log('SEARCH CALLED v.%s', VERSION_NO)\n self.Log('SEARCH - media.title - %s', media.title)\n self.Log('SEARCH - media.items[0].parts[0].file - %s',\n media.items[0].parts[0].file)\n self.Log('SEARCH - media.primary_metadata.title - %s',\n media.primary_metadata.title)\n self.Log('SEARCH - media.items - %s', media.items)\n self.Log('SEARCH - media.filename - %s', media.filename)\n self.Log('SEARCH - lang - %s', lang)\n self.Log('SEARCH - manual - %s', manual)\n\n if media.items[0].parts[0].file is not None:\n path_and_file = media.items[0].parts[0].file\n self.Log('SEARCH - File Path: %s' % path_and_file)\n filename = os.path.basename(path_and_file)\n dirname = os.path.dirname(path_and_file)\n\n metadata_file = os.path.join(dirname, '.' + filename + '.metadata')\n if os.path.isfile(metadata_file):\n self.Log('SEARCH - Exact Match \"%s\" == \"%s\"' %\n (filename, metadata_file))\n results.Append(MetadataSearchResult(id=metadata_file,\n name=filename,\n score=100, lang=lang))\n return\n\n def update(self, metadata, media, lang, force=False):\n self.Log('UPDATE CALLED')\n\n if media.items[0].parts[0].file is not None:\n file_path = media.items[0].parts[0].file\n self.Log('UPDATE - File Path: %s' % file_path)\n self.Log('UPDATE - metadata.id: %s' % metadata.id)\n\n metadata_dict = json.loads(Data.Load(metadata.id))\n\n # Set tagline to URL\n metadata.tagline = metadata_dict[\"description_url\"]\n video_title = metadata_dict[\"title\"]\n\n self.Log('UPDATE - video_title: \"%s\"' % video_title)\n\n # Update thumbnail and cover data\n valid_image_names = []\n i = 0\n self.Log(\"UPDATE - video_image_list\")\n try:\n coverPrefs = int(Prefs['cover'])\n except ValueError:\n coverPrefs = None\n\n try:\n for thumb_url, poster_url in \\\n metadata_dict[\"posters\"].iteritems():\n if coverPrefs and i > coverPrefs:\n break\n self.Log('UPDATE - thumb_url: \"%s\"' % thumb_url)\n self.Log('UPDATE - poster_url: \"%s\"' % poster_url)\n valid_image_names.append(poster_url)\n if poster_url not in metadata.posters:\n try:\n i += 1\n metadata.posters[poster_url] = \\\n Proxy.Preview(HTTP.Request(thumb_url),\n sort_order=i)\n except:\n pass\n metadata.posters.validate_keys(valid_image_names)\n except Exception as e:\n self.Log('UPDATE - Error getting posters: %s' % e)\n pass\n\n # Try to get description text\n about_text = metadata_dict[\"description\"]\n self.Log('UPDATE - About Text: %s', about_text)\n metadata.summary = about_text\n\n # Try to get release date\n # TODO: Release Date?\n\n # Try to get and process the video cast\n metadata.roles.clear()\n if \"actor\" in metadata_dict[\"roles\"]:\n actors = metadata_dict[\"roles\"][\"actor\"]\n self.Log('UPDATE - cast: \"%s\"' % actors)\n for actor in actors:\n actor = actor.strip()\n if (len(actor) > 0):\n role = metadata.roles.new()\n role.name = actor\n\n # Try to get and process the video genres\n metadata.genres.clear()\n genres = metadata_dict[\"categories\"]\n self.Log('UPDATE - video_genres: \"%s\"' % genres)\n for genre in genres:\n genre = genre.strip()\n if (len(genre) > 0):\n metadata.genres.add(genre)\n\n metadata.rating = metadata_dict[\"user_rating\"]\n metadata.content_rating = metadata_dict[\"content_rating\"]\n metadata.title = video_title\n metadata.studio = \"Bel Ami\"\n","sub_path":"LocalDotfile.bundle/Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"170281998","text":"class Node:\n def __init__(self, id):\n self.id = id\n self.parent = None\n self.left = None\n self.right = None\n self.height = None\n self.depth = None\n\n def type(self):\n if self.parent is None:\n return \"root\"\n if self.left is None and self.right is None:\n return \"leaf\"\n return \"internal node\"\n \n def get_parent_id(self):\n if self.parent is None:\n return -1\n return self.parent.id\n \n def get_sibling_id(self):\n if self.parent is None:\n return -1\n if self.parent.left is not None and self.parent.left.id != self.id:\n return self.parent.left.id\n if self.parent.right is not None and self.parent.right.id != self.id:\n return self.parent.right.id\n return -1\n \n def get_degree(self):\n degree = 0\n if self.left is not None:\n degree += 1\n if self.right is not None:\n degree += 1\n return degree\n \n def get_height(self):\n if self.height is not None:\n return self.height\n \n height = 0\n if self.left is not None:\n height = self.left.get_height() + 1\n if self.right is not None:\n right_height = self.right.get_height() + 1\n if height < right_height:\n height = right_height\n self.height = height\n return height\n\n def get_depth(self):\n if self.depth is not None:\n return self.depth\n depth = 0\n if self.parent is not None:\n depth = self.parent.get_depth() + 1\n self.depth = depth\n return depth\n\n def __str__(self):\n return \"node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}\".format(\n self.id, self.get_parent_id(), self.get_sibling_id(), self.get_degree(), self.get_depth(), self.get_height(), self.type()\n )\n\n\n# ALDS1_7_A: 2分木\ndef main():\n n = int(input())\n nodes = [ Node(i) for i in range(0, n)]\n for _ in range(0, n):\n items = [int(v) for v in input().split(\" \")]\n id = items[0]\n left = items[1]\n right = items[2]\n node = nodes[id]\n if left != -1:\n left_node = nodes[left]\n left_node.parent = node\n node.left = left_node\n if right != -1:\n right_node = nodes[right]\n right_node.parent = node\n node.right = right_node\n for n in nodes:\n print(str(n))\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"aoj/src/ALDS1_7_B/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"397723966","text":"'''\nUnit2 Lesson3: Linear Regression and Correlation\n'''\n\nimport pandas as pd\nimport plots\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nimport numpy as np\n\nds_loans = pd.read_csv(\"loansData.csv\")\n# print(ds_loans.head(5))\nprint(ds_loans.info())\nds_loans = ds_loans.dropna()\n\nfico = \"FICO.Score\"\nfico_name = fico.replace(\".\", \" \")\nint_rate = \"Interest.Rate\"\nint_rate_name = int_rate.replace(\".\", \" \")\nlength = \"Loan.Length\"\nlength_name = length.replace(\".\", \" \")\namt_req = \"Amount.Requested\"\namt_req_name = amt_req.replace(\".\", \" \")\nincome = \"Monthly.Income\"\nincome_name = income.replace(\".\", \" \")\n\nds_loans[fico] = ds_loans[\"FICO.Range\"].map(lambda x: int(str(x).rstrip().split(\"-\")[0]))\nds_loans[int_rate] = ds_loans[int_rate].map(lambda x: float(str(x).rstrip()[:-1])/100)\nds_loans[length] = ds_loans[length].map(lambda x: int(str(x).rstrip().split(\" \")[0]))\n\nds_loans.to_csv(\"loansData_clean.csv\", header=True, index=False)\n\n# for col in [fico, int_rate, length]:\n # print(ds_loans[col][:5])\ndef base_data_plots():\n # plots.all_plots(ds_loans[fico], \"Fico Scores\", \"no unit\")\n # plots.all_plots(ds_loans[int_rate], \"Interest Rates\", \"%\")\n # plots.all_plots(ds_loans[length], \"Loan Length\", \"months\")\n fig = plt.figure(\"Base data\")\n ax1 = fig.add_subplot(221)\n ax1.hist(ds_loans[fico])\n ax1.set_title(\"FICO scores\")\n ax2 = fig.add_subplot(222)\n ax2.hist(ds_loans[int_rate])\n ax2.set_title(\"Interest Rate\")\n ax3 = fig.add_subplot(223)\n ax3.hist(ds_loans[length])\n ax3.set_title(\"Loan Length (months)\")\n plt.show()\n\n# base_data_plots()\n\ndef scatter_matrix_plot():\n # spm = pd.scatter_matrix(ds_loans, figsize=(10,10), diagonal='hist', alpha=0.05)\n spm_reduced = pd.scatter_matrix(ds_loans[[fico, int_rate, length, amt_req, income]], figsize=(10,10), diagonal='hist', alpha=0.05)\n plt.show()\n \n# scatter_matrix_plot()\n\n#y=interest rate, x1=FICO score, x2=Loan amount\n#transpose to have data in a vertical vector form\ny = np.matrix(ds_loans[int_rate]).transpose()\nx1 = np.matrix(ds_loans[fico]).transpose()\nx2 = np.matrix(ds_loans[amt_req]).transpose()\n#create a single matrix from x1 and x2\nx = np.column_stack([x1, x2])\n#add a constant to x to have the full equation: y = a1*x1 + a2*x2 + b\nX = sm.add_constant(x)\n\n#create the linear model and fit\nmodel = sm.OLS(y, X).fit() #OLS: Ordinary Least Square\nprint(\"\\nInterest_Rate = Cst + a1*Fico + a2*Loan_Amount:\\n\")\nprint(model.summary())\n# print(dir(model))\n\n#get model parameters\n(cst, a1, a2) = (model.params[0], model.params[1], model.params[2])\nprint(\"\\nInterest_Rate = Cst + a1*Fico + a2*Loan_Amount\")\nprint(\"\\nModel parameters:\\n\\tCst = {0}\\n\\ta1 = {1}\\n\\ta2 = {2}\".format(cst, a1, a2))\n\n#create a modeled interest rate\nds_loans[\"Predicted_interest_rate\"] = cst + a1*x1 + a2*x2\n# int_rate_model = cst + a1*x1 + a2*x2\ndef scatter_data_vs_model(predicted, ylabel):\n plt.scatter(ds_loans[int_rate], predicted)\n # plt.plot(ds_loans[int_rate], ds_loans[int_rate], color='r')\n plt.plot([0, 0.3], [0, 0.3], color='r', linewidth=2)\n plt.xlim([0, 0.3])\n plt.ylim([0, 0.3])\n plt.xlabel(\"Interest rate from data\")\n plt.ylabel(ylabel)\n\n# scatter_data_vs_model(ds_loans[\"Predicted_interest_rate\"], \"Model1\")\n# plt.show()\n \n#Linear regression with one more input: monthly income\nx3 = np.matrix(ds_loans[income]).transpose()\nx_2 = np.column_stack([x1, x2, x3])\nX_2 = sm.add_constant(x_2)\nmodel_2 = sm.OLS(y, X_2).fit()\nprint(model_2.summary())\n(cst_2, a1_2, a2_2, a3_2) = (model_2.params[0], model_2.params[1], model_2.params[2], model_2.params[3])\nprint(\"\\nInterest_Rate = Cst + a1*Fico + a2*Loan_Amount + a3*Montthly_Income\")\nprint(\"\\nModel parameters:\\n\\tCst = {0}\\n\\ta1 = {1}\\n\\ta2 = {2}\\n\\ta3 = {3}\".format(cst_2, a1_2, a2_2, a3_2))\nds_loans[\"Predicted_interest_rate_2\"] = cst_2 + a1_2*x1 + a2_2*x2 + a3_2*x3\n# scatter_data_vs_model(ds_loans[\"Predicted_interest_rate_2\"], \"Model2\")\n# plt.show()\n# print(model_2.)\n\nfig = plt.figure()\nplt.subplot(1,2,1)\nscatter_data_vs_model(ds_loans[\"Predicted_interest_rate\"], \"Model1 - LR(FICO, Loan Amount)\")\nfig.text(.15, .83, \"R^2 = {0}\".format(round(model.rsquared, 4)))\nplt.subplot(1,2,2)\nscatter_data_vs_model(ds_loans[\"Predicted_interest_rate_2\"], \"Model2 - LR(FICO, Loan Amount, Monthly Income)\")\nfig.text(.58, .83, \"R^2 = {0}\".format(round(model_2.rsquared, 4)))\nplt.show()","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"421401364","text":"import scrapy\nimport json\nimport re\nimport io\n\n\nclass QuotesSpider(scrapy.Spider):\n name = \"quotes\"\n\n start_urls = []\n\n baseurl = 'https://www.margonem.pl/?task=profile&id='\n\n json_file = open('./tutorial/general_stats/id_list_total.json')\n json_str = json_file.read()\n json_data = json.loads(json_str)\n\n last_id_from_json = json_data[-1]\n\n for i in json_data:\n start_urls.append(baseurl+str(i))\n\n for i in range(last_id_from_json+1,9130000):\n start_urls.append(baseurl+str(i))\n\n def parse(self, response):\n page = response.url.split(\"=\")[-1]\n\n wsp = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[7]/div/text()').get()\n wsp = wsp[-len(wsp):-4] # removing unnecessary \" [?]\"\n\n posts = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[5]/div/text()').get()\n\n function = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[1]/div/text()').get()\n \n rep = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[6]/div/text()').get()\n\n created = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[3]/div/text()').get()\n created = created.split(\" \")[0]\n\n lastlogin = response.xpath('//div[@id=\"inside_bar_left_stats_profile\"]/div[4]/div/text()').get()\n\n nick = response.xpath('//p[@id=\"nick\"]/@tip').get()\n\n text = response.xpath('//body').extract()\n\n #bany\n found_or_no = [m.start() for m in re.finditer('\"color:red\">Konto czasowo zablokowane', str(text))]\n if not found_or_no:\n status = \" \"\n else:\n status = \"temp ban\"\n\n found_or_no = [m.start() for m in re.finditer('\"color:red\">Konto zablokowane', str(text))]\n if found_or_no:\n status = \"perm ban\"\n\n found_or_no = [m.start() for m in re.finditer('\"color:red\">Aktywny knebel na forum', str(text))]\n if found_or_no:\n status = \"knebel\"\n\n #kb\n found_or_no = [m.start() for m in re.finditer('>|[-+*/%^|&<>]', Operator),\n (r'\\d+#[\\da-zA-Z]+', Number),\n (r'\\d+#(?! )', Number),\n (r'0[xX][\\da-fA-F]+', Number),\n (r'\\d+', Number),\n (r'[a-zA-Z_]\\w*', Name.Variable), # user variable\n include('root'),\n ],\n 'backticks': [\n (r'`', String.Backtick, '#pop'),\n include('root'),\n ],\n }\n\n def analyse_text(text):\n if shebang_matches(text, r'(ba|z|)sh'):\n return 1\n if text.startswith('$ '):\n return 0.2\n\n\nclass SlurmBashLexer(BashLexer):\n \"\"\"\n Lexer for (ba|k|z|)sh Slurm scripts.\n\n .. versionadded:: 2.4\n \"\"\"\n\n name = 'Slurm'\n aliases = ['slurm', 'sbatch']\n filenames = ['*.sl']\n mimetypes = []\n EXTRA_KEYWORDS = {'srun'}\n\n def get_tokens_unprocessed(self, text):\n for index, token, value in BashLexer.get_tokens_unprocessed(self, text):\n if token is Text and value in self.EXTRA_KEYWORDS:\n yield index, Name.Builtin, value\n elif token is Comment.Single and 'SBATCH' in value:\n yield index, Keyword.Pseudo, value\n else:\n yield index, token, value\n\n\nclass ShellSessionBaseLexer(Lexer):\n \"\"\"\n Base lexer for shell sessions.\n\n .. versionadded:: 2.1\n \"\"\"\n\n _bare_continuation = False\n _venv = re.compile(r'^(\\([^)]*\\))(\\s*)')\n\n def get_tokens_unprocessed(self, text):\n innerlexer = self._innerLexerCls(**self.options)\n\n pos = 0\n curcode = ''\n insertions = []\n backslash_continuation = False\n\n for match in line_re.finditer(text):\n line = match.group()\n\n venv_match = self._venv.match(line)\n if venv_match:\n venv = venv_match.group(1)\n venv_whitespace = venv_match.group(2)\n insertions.append((len(curcode),\n [(0, Generic.Prompt.VirtualEnv, venv)]))\n if venv_whitespace:\n insertions.append((len(curcode),\n [(0, Text, venv_whitespace)]))\n line = line[venv_match.end():]\n\n m = self._ps1rgx.match(line)\n if m:\n # To support output lexers (say diff output), the output\n # needs to be broken by prompts whenever the output lexer\n # changes.\n if not insertions:\n pos = match.start()\n\n insertions.append((len(curcode),\n [(0, Generic.Prompt, m.group(1))]))\n curcode += m.group(2)\n backslash_continuation = curcode.endswith('\\\\\\n')\n elif backslash_continuation:\n if line.startswith(self._ps2):\n insertions.append((len(curcode),\n [(0, Generic.Prompt,\n line[:len(self._ps2)])]))\n curcode += line[len(self._ps2):]\n else:\n curcode += line\n backslash_continuation = curcode.endswith('\\\\\\n')\n elif self._bare_continuation and line.startswith(self._ps2):\n insertions.append((len(curcode),\n [(0, Generic.Prompt,\n line[:len(self._ps2)])]))\n curcode += line[len(self._ps2):]\n else:\n if insertions:\n toks = innerlexer.get_tokens_unprocessed(curcode)\n for i, t, v in do_insertions(insertions, toks):\n yield pos+i, t, v\n yield match.start(), Generic.Output, line\n insertions = []\n curcode = ''\n if insertions:\n for i, t, v in do_insertions(insertions,\n innerlexer.get_tokens_unprocessed(curcode)):\n yield pos+i, t, v\n\n\nclass BashSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for Bash shell sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 1.1\n \"\"\"\n\n name = 'Bash Session'\n aliases = ['console', 'shell-session']\n filenames = ['*.sh-session', '*.shell-session']\n mimetypes = ['application/x-shell-session', 'application/x-sh-session']\n\n _innerLexerCls = BashLexer\n _ps1rgx = re.compile(\n r'^((?:(?:\\[.*?\\])|(?:\\(\\S+\\))?(?:| |sh\\S*?|\\w+\\S+[@:]\\S+(?:\\s+\\S+)' \\\n r'?|\\[\\S+[@:][^\\n]+\\].+))\\s*[$#%]\\s*)(.*\\n?)')\n _ps2 = '> '\n\n\nclass BatchLexer(RegexLexer):\n \"\"\"\n Lexer for the DOS/Windows Batch file format.\n\n .. versionadded:: 0.7\n \"\"\"\n name = 'Batchfile'\n aliases = ['batch', 'bat', 'dosbatch', 'winbatch']\n filenames = ['*.bat', '*.cmd']\n mimetypes = ['application/x-dos-batch']\n\n flags = re.MULTILINE | re.IGNORECASE\n\n _nl = r'\\n\\x1a'\n _punct = r'&<>|'\n _ws = r'\\t\\v\\f\\r ,;=\\xa0'\n _nlws = r'\\s\\x1a\\xa0,;='\n _space = r'(?:(?:(?:\\^[%s])?[%s])+)' % (_nl, _ws)\n _keyword_terminator = (r'(?=(?:\\^[%s]?)?[%s+./:[\\\\\\]]|[%s%s(])' %\n (_nl, _ws, _nl, _punct))\n _token_terminator = r'(?=\\^?[%s]|[%s%s])' % (_ws, _punct, _nl)\n _start_label = r'((?:(?<=^[^:])|^[^:]?)[%s]*)(:)' % _ws\n _label = r'(?:(?:[^%s%s+:^]|\\^[%s]?[\\w\\W])*)' % (_nlws, _punct, _nl)\n _label_compound = r'(?:(?:[^%s%s+:^)]|\\^[%s]?[^)])*)' % (_nlws, _punct, _nl)\n _number = r'(?:-?(?:0[0-7]+|0x[\\da-f]+|\\d+)%s)' % _token_terminator\n _opword = r'(?:equ|geq|gtr|leq|lss|neq)'\n _string = r'(?:\"[^%s\"]*(?:\"|(?=[%s])))' % (_nl, _nl)\n _variable = (r'(?:(?:%%(?:\\*|(?:~[a-z]*(?:\\$[^:]+:)?)?\\d|'\n r'[^%%:%s]+(?::(?:~(?:-?\\d+)?(?:,(?:-?\\d+)?)?|(?:[^%%%s^]|'\n r'\\^[^%%%s])[^=%s]*=(?:[^%%%s^]|\\^[^%%%s])*)?)?%%))|'\n r'(?:\\^?![^!:%s]+(?::(?:~(?:-?\\d+)?(?:,(?:-?\\d+)?)?|(?:'\n r'[^!%s^]|\\^[^!%s])[^=%s]*=(?:[^!%s^]|\\^[^!%s])*)?)?\\^?!))' %\n (_nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl, _nl))\n _core_token = r'(?:(?:(?:\\^[%s]?)?[^\"%s%s])+)' % (_nl, _nlws, _punct)\n _core_token_compound = r'(?:(?:(?:\\^[%s]?)?[^\"%s%s)])+)' % (_nl, _nlws, _punct)\n _token = r'(?:[%s]+|%s)' % (_punct, _core_token)\n _token_compound = r'(?:[%s]+|%s)' % (_punct, _core_token_compound)\n _stoken = (r'(?:[%s]+|(?:%s|%s|%s)+)' %\n (_punct, _string, _variable, _core_token))\n\n def _make_begin_state(compound, _core_token=_core_token,\n _core_token_compound=_core_token_compound,\n _keyword_terminator=_keyword_terminator,\n _nl=_nl, _punct=_punct, _string=_string,\n _space=_space, _start_label=_start_label,\n _stoken=_stoken, _token_terminator=_token_terminator,\n _variable=_variable, _ws=_ws):\n rest = '(?:%s|%s|[^\"%%%s%s%s])*' % (_string, _variable, _nl, _punct,\n ')' if compound else '')\n rest_of_line = r'(?:(?:[^%s^]|\\^[%s]?[\\w\\W])*)' % (_nl, _nl)\n rest_of_line_compound = r'(?:(?:[^%s^)]|\\^[%s]?[^)])*)' % (_nl, _nl)\n set_space = r'((?:(?:\\^[%s]?)?[^\\S\\n])*)' % _nl\n suffix = ''\n if compound:\n _keyword_terminator = r'(?:(?=\\))|%s)' % _keyword_terminator\n _token_terminator = r'(?:(?=\\))|%s)' % _token_terminator\n suffix = '/compound'\n return [\n ((r'\\)', Punctuation, '#pop') if compound else\n (r'\\)((?=\\()|%s)%s' % (_token_terminator, rest_of_line),\n Comment.Single)),\n (r'(?=%s)' % _start_label, Text, 'follow%s' % suffix),\n (_space, using(this, state='text')),\n include('redirect%s' % suffix),\n (r'[%s]+' % _nl, Text),\n (r'\\(', Punctuation, 'root/compound'),\n (r'@+', Punctuation),\n (r'((?:for|if|rem)(?:(?=(?:\\^[%s]?)?/)|(?:(?!\\^)|'\n r'(?<=m))(?:(?=\\()|%s)))(%s?%s?(?:\\^[%s]?)?/(?:\\^[%s]?)?\\?)' %\n (_nl, _token_terminator, _space,\n _core_token_compound if compound else _core_token, _nl, _nl),\n bygroups(Keyword, using(this, state='text')),\n 'follow%s' % suffix),\n (r'(goto%s)(%s(?:\\^[%s]?)?/(?:\\^[%s]?)?\\?%s)' %\n (_keyword_terminator, rest, _nl, _nl, rest),\n bygroups(Keyword, using(this, state='text')),\n 'follow%s' % suffix),\n (words(('assoc', 'break', 'cd', 'chdir', 'cls', 'color', 'copy',\n 'date', 'del', 'dir', 'dpath', 'echo', 'endlocal', 'erase',\n 'exit', 'ftype', 'keys', 'md', 'mkdir', 'mklink', 'move',\n 'path', 'pause', 'popd', 'prompt', 'pushd', 'rd', 'ren',\n 'rename', 'rmdir', 'setlocal', 'shift', 'start', 'time',\n 'title', 'type', 'ver', 'verify', 'vol'),\n suffix=_keyword_terminator), Keyword, 'follow%s' % suffix),\n (r'(call)(%s?)(:)' % _space,\n bygroups(Keyword, using(this, state='text'), Punctuation),\n 'call%s' % suffix),\n (r'call%s' % _keyword_terminator, Keyword),\n (r'(for%s(?!\\^))(%s)(/f%s)' %\n (_token_terminator, _space, _token_terminator),\n bygroups(Keyword, using(this, state='text'), Keyword),\n ('for/f', 'for')),\n (r'(for%s(?!\\^))(%s)(/l%s)' %\n (_token_terminator, _space, _token_terminator),\n bygroups(Keyword, using(this, state='text'), Keyword),\n ('for/l', 'for')),\n (r'for%s(?!\\^)' % _token_terminator, Keyword, ('for2', 'for')),\n (r'(goto%s)(%s?)(:?)' % (_keyword_terminator, _space),\n bygroups(Keyword, using(this, state='text'), Punctuation),\n 'label%s' % suffix),\n (r'(if(?:(?=\\()|%s)(?!\\^))(%s?)((?:/i%s)?)(%s?)((?:not%s)?)(%s?)' %\n (_token_terminator, _space, _token_terminator, _space,\n _token_terminator, _space),\n bygroups(Keyword, using(this, state='text'), Keyword,\n using(this, state='text'), Keyword,\n using(this, state='text')), ('(?', 'if')),\n (r'rem(((?=\\()|%s)%s?%s?.*|%s%s)' %\n (_token_terminator, _space, _stoken, _keyword_terminator,\n rest_of_line_compound if compound else rest_of_line),\n Comment.Single, 'follow%s' % suffix),\n (r'(set%s)%s(/a)' % (_keyword_terminator, set_space),\n bygroups(Keyword, using(this, state='text'), Keyword),\n 'arithmetic%s' % suffix),\n (r'(set%s)%s((?:/p)?)%s((?:(?:(?:\\^[%s]?)?[^\"%s%s^=%s]|'\n r'\\^[%s]?[^\"=])+)?)((?:(?:\\^[%s]?)?=)?)' %\n (_keyword_terminator, set_space, set_space, _nl, _nl, _punct,\n ')' if compound else '', _nl, _nl),\n bygroups(Keyword, using(this, state='text'), Keyword,\n using(this, state='text'), using(this, state='variable'),\n Punctuation),\n 'follow%s' % suffix),\n default('follow%s' % suffix)\n ]\n\n def _make_follow_state(compound, _label=_label,\n _label_compound=_label_compound, _nl=_nl,\n _space=_space, _start_label=_start_label,\n _token=_token, _token_compound=_token_compound,\n _ws=_ws):\n suffix = '/compound' if compound else ''\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state += [\n (r'%s([%s]*)(%s)(.*)' %\n (_start_label, _ws, _label_compound if compound else _label),\n bygroups(Text, Punctuation, Text, Name.Label, Comment.Single)),\n include('redirect%s' % suffix),\n (r'(?=[%s])' % _nl, Text, '#pop'),\n (r'\\|\\|?|&&?', Punctuation, '#pop'),\n include('text')\n ]\n return state\n\n def _make_arithmetic_state(compound, _nl=_nl, _punct=_punct,\n _string=_string, _variable=_variable,\n _ws=_ws, _nlws=_nlws):\n op = r'=+\\-*/!~'\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state += [\n (r'0[0-7]+', Number.Oct),\n (r'0x[\\da-f]+', Number.Hex),\n (r'\\d+', Number.Integer),\n (r'[(),]+', Punctuation),\n (r'([%s]|%%|\\^\\^)+' % op, Operator),\n (r'(%s|%s|(\\^[%s]?)?[^()%s%%\\^\"%s%s]|\\^[%s]?%s)+' %\n (_string, _variable, _nl, op, _nlws, _punct, _nlws,\n r'[^)]' if compound else r'[\\w\\W]'),\n using(this, state='variable')),\n (r'(?=[\\x00|&])', Text, '#pop'),\n include('follow')\n ]\n return state\n\n def _make_call_state(compound, _label=_label,\n _label_compound=_label_compound):\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state.append((r'(:?)(%s)' % (_label_compound if compound else _label),\n bygroups(Punctuation, Name.Label), '#pop'))\n return state\n\n def _make_label_state(compound, _label=_label,\n _label_compound=_label_compound, _nl=_nl,\n _punct=_punct, _string=_string, _variable=_variable):\n state = []\n if compound:\n state.append((r'(?=\\))', Text, '#pop'))\n state.append((r'(%s?)((?:%s|%s|\\^[%s]?%s|[^\"%%^%s%s%s])*)' %\n (_label_compound if compound else _label, _string,\n _variable, _nl, r'[^)]' if compound else r'[\\w\\W]', _nl,\n _punct, r')' if compound else ''),\n bygroups(Name.Label, Comment.Single), '#pop'))\n return state\n\n def _make_redirect_state(compound,\n _core_token_compound=_core_token_compound,\n _nl=_nl, _punct=_punct, _stoken=_stoken,\n _string=_string, _space=_space,\n _variable=_variable, _nlws=_nlws):\n stoken_compound = (r'(?:[%s]+|(?:%s|%s|%s)+)' %\n (_punct, _string, _variable, _core_token_compound))\n return [\n (r'((?:(?<=[%s])\\d)?)(>>?&|<&)([%s]*)(\\d)' %\n (_nlws, _nlws),\n bygroups(Number.Integer, Punctuation, Text, Number.Integer)),\n (r'((?:(?<=[%s])(?>?|<)(%s?%s)' %\n (_nlws, _nl, _space, stoken_compound if compound else _stoken),\n bygroups(Number.Integer, Punctuation, using(this, state='text')))\n ]\n\n tokens = {\n 'root': _make_begin_state(False),\n 'follow': _make_follow_state(False),\n 'arithmetic': _make_arithmetic_state(False),\n 'call': _make_call_state(False),\n 'label': _make_label_state(False),\n 'redirect': _make_redirect_state(False),\n 'root/compound': _make_begin_state(True),\n 'follow/compound': _make_follow_state(True),\n 'arithmetic/compound': _make_arithmetic_state(True),\n 'call/compound': _make_call_state(True),\n 'label/compound': _make_label_state(True),\n 'redirect/compound': _make_redirect_state(True),\n 'variable-or-escape': [\n (_variable, Name.Variable),\n (r'%%%%|\\^[%s]?(\\^!|[\\w\\W])' % _nl, String.Escape)\n ],\n 'string': [\n (r'\"', String.Double, '#pop'),\n (_variable, Name.Variable),\n (r'\\^!|%%', String.Escape),\n (r'[^\"%%^%s]+|[%%^]' % _nl, String.Double),\n default('#pop')\n ],\n 'sqstring': [\n include('variable-or-escape'),\n (r'[^%]+|%', String.Single)\n ],\n 'bqstring': [\n include('variable-or-escape'),\n (r'[^%]+|%', String.Backtick)\n ],\n 'text': [\n (r'\"', String.Double, 'string'),\n include('variable-or-escape'),\n (r'[^\"%%^%s%s\\d)]+|.' % (_nlws, _punct), Text)\n ],\n 'variable': [\n (r'\"', String.Double, 'string'),\n include('variable-or-escape'),\n (r'[^\"%%^%s]+|.' % _nl, Name.Variable)\n ],\n 'for': [\n (r'(%s)(in)(%s)(\\()' % (_space, _space),\n bygroups(using(this, state='text'), Keyword,\n using(this, state='text'), Punctuation), '#pop'),\n include('follow')\n ],\n 'for2': [\n (r'\\)', Punctuation),\n (r'(%s)(do%s)' % (_space, _token_terminator),\n bygroups(using(this, state='text'), Keyword), '#pop'),\n (r'[%s]+' % _nl, Text),\n include('follow')\n ],\n 'for/f': [\n (r'(\")((?:%s|[^\"])*?\")([%s]*)(\\))' % (_variable, _nlws),\n bygroups(String.Double, using(this, state='string'), Text,\n Punctuation)),\n (r'\"', String.Double, ('#pop', 'for2', 'string')),\n (r\"('(?:%%%%|%s|[\\w\\W])*?')([%s]*)(\\))\" % (_variable, _nlws),\n bygroups(using(this, state='sqstring'), Text, Punctuation)),\n (r'(`(?:%%%%|%s|[\\w\\W])*?`)([%s]*)(\\))' % (_variable, _nlws),\n bygroups(using(this, state='bqstring'), Text, Punctuation)),\n include('for2')\n ],\n 'for/l': [\n (r'-?\\d+', Number.Integer),\n include('for2')\n ],\n 'if': [\n (r'((?:cmdextversion|errorlevel)%s)(%s)(\\d+)' %\n (_token_terminator, _space),\n bygroups(Keyword, using(this, state='text'),\n Number.Integer), '#pop'),\n (r'(defined%s)(%s)(%s)' % (_token_terminator, _space, _stoken),\n bygroups(Keyword, using(this, state='text'),\n using(this, state='variable')), '#pop'),\n (r'(exist%s)(%s%s)' % (_token_terminator, _space, _stoken),\n bygroups(Keyword, using(this, state='text')), '#pop'),\n (r'(%s%s)(%s)(%s%s)' % (_number, _space, _opword, _space, _number),\n bygroups(using(this, state='arithmetic'), Operator.Word,\n using(this, state='arithmetic')), '#pop'),\n (_stoken, using(this, state='text'), ('#pop', 'if2')),\n ],\n 'if2': [\n (r'(%s?)(==)(%s?%s)' % (_space, _space, _stoken),\n bygroups(using(this, state='text'), Operator,\n using(this, state='text')), '#pop'),\n (r'(%s)(%s)(%s%s)' % (_space, _opword, _space, _stoken),\n bygroups(using(this, state='text'), Operator.Word,\n using(this, state='text')), '#pop')\n ],\n '(?': [\n (_space, using(this, state='text')),\n (r'\\(', Punctuation, ('#pop', 'else?', 'root/compound')),\n default('#pop')\n ],\n 'else?': [\n (_space, using(this, state='text')),\n (r'else%s' % _token_terminator, Keyword, '#pop'),\n default('#pop')\n ]\n }\n\n\nclass MSDOSSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for MS DOS shell sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'MSDOS Session'\n aliases = ['doscon']\n filenames = []\n mimetypes = []\n\n _innerLexerCls = BatchLexer\n _ps1rgx = re.compile(r'^([^>]*>)(.*\\n?)')\n _ps2 = 'More? '\n\n\nclass TcshLexer(RegexLexer):\n \"\"\"\n Lexer for tcsh scripts.\n\n .. versionadded:: 0.10\n \"\"\"\n\n name = 'Tcsh'\n aliases = ['tcsh', 'csh']\n filenames = ['*.tcsh', '*.csh']\n mimetypes = ['application/x-csh']\n\n tokens = {\n 'root': [\n include('basic'),\n (r'\\$\\(', Keyword, 'paren'),\n (r'\\$\\{#?', Keyword, 'curly'),\n (r'`', String.Backtick, 'backticks'),\n include('data'),\n ],\n 'basic': [\n (r'\\b(if|endif|else|while|then|foreach|case|default|'\n r'break|continue|goto|breaksw|end|switch|endsw)\\s*\\b',\n Keyword),\n (r'\\b(alias|alloc|bg|bindkey|builtins|bye|caller|cd|chdir|'\n r'complete|dirs|echo|echotc|eval|exec|exit|fg|filetest|getxvers|'\n r'glob|getspath|hashstat|history|hup|inlib|jobs|kill|'\n r'limit|log|login|logout|ls-F|migrate|newgrp|nice|nohup|notify|'\n r'onintr|popd|printenv|pushd|rehash|repeat|rootnode|popd|pushd|'\n r'set|shift|sched|setenv|setpath|settc|setty|setxvers|shift|'\n r'source|stop|suspend|source|suspend|telltc|time|'\n r'umask|unalias|uncomplete|unhash|universe|unlimit|unset|unsetenv|'\n r'ver|wait|warp|watchlog|where|which)\\s*\\b',\n Name.Builtin),\n (r'#.*', Comment),\n (r'\\\\[\\w\\W]', String.Escape),\n (r'(\\b\\w+)(\\s*)(=)', bygroups(Name.Variable, Text, Operator)),\n (r'[\\[\\]{}()=]+', Operator),\n (r'<<\\s*(\\'?)\\\\?(\\w+)[\\w\\W]+?\\2', String),\n (r';', Punctuation),\n ],\n 'data': [\n (r'(?s)\"(\\\\\\\\|\\\\[0-7]+|\\\\.|[^\"\\\\])*\"', String.Double),\n (r\"(?s)'(\\\\\\\\|\\\\[0-7]+|\\\\.|[^'\\\\])*'\", String.Single),\n (r'\\s+', Text),\n (r'[^=\\s\\[\\]{}()$\"\\'`\\\\;#]+', Text),\n (r'\\d+(?= |\\Z)', Number),\n (r'\\$#?(\\w+|.)', Name.Variable),\n ],\n 'curly': [\n (r'\\}', Keyword, '#pop'),\n (r':-', Keyword),\n (r'\\w+', Name.Variable),\n (r'[^}:\"\\'`$]+', Punctuation),\n (r':', Punctuation),\n include('root'),\n ],\n 'paren': [\n (r'\\)', Keyword, '#pop'),\n include('root'),\n ],\n 'backticks': [\n (r'`', String.Backtick, '#pop'),\n include('root'),\n ],\n }\n\n\nclass TcshSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for Tcsh sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'Tcsh Session'\n aliases = ['tcshcon']\n filenames = []\n mimetypes = []\n\n _innerLexerCls = TcshLexer\n _ps1rgx = re.compile(r'^([^>]+>)(.*\\n?)')\n _ps2 = '? '\n\n\nclass PowerShellLexer(RegexLexer):\n \"\"\"\n For Windows PowerShell code.\n\n .. versionadded:: 1.5\n \"\"\"\n name = 'PowerShell'\n aliases = ['powershell', 'pwsh', 'posh', 'ps1', 'psm1']\n filenames = ['*.ps1', '*.psm1']\n mimetypes = ['text/x-powershell']\n\n flags = re.DOTALL | re.IGNORECASE | re.MULTILINE\n\n keywords = (\n 'while validateset validaterange validatepattern validatelength '\n 'validatecount until trap switch return ref process param parameter in '\n 'if global: local: function foreach for finally filter end elseif else '\n 'dynamicparam do default continue cmdletbinding break begin alias \\\\? '\n '% #script #private #local #global mandatory parametersetname position '\n 'valuefrompipeline valuefrompipelinebypropertyname '\n 'valuefromremainingarguments helpmessage try catch throw').split()\n\n operators = (\n 'and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle '\n 'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains '\n 'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt '\n 'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like '\n 'lt match ne not notcontains notlike notmatch or regex replace '\n 'wildcard').split()\n\n verbs = (\n 'write where watch wait use update unregister unpublish unprotect '\n 'unlock uninstall undo unblock trace test tee take sync switch '\n 'suspend submit stop step start split sort skip show set send select '\n 'search scroll save revoke resume restore restart resolve resize '\n 'reset request repair rename remove register redo receive read push '\n 'publish protect pop ping out optimize open new move mount merge '\n 'measure lock limit join invoke install initialize import hide group '\n 'grant get format foreach find export expand exit enter enable edit '\n 'dismount disconnect disable deny debug cxnew copy convertto '\n 'convertfrom convert connect confirm compress complete compare close '\n 'clear checkpoint block backup assert approve aggregate add').split()\n\n aliases_ = (\n 'ac asnp cat cd cfs chdir clc clear clhy cli clp cls clv cnsn '\n 'compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo epal '\n 'epcsv epsn erase etsn exsn fc fhx fl foreach ft fw gal gbp gc gci gcm '\n 'gcs gdr ghy gi gjb gl gm gmo gp gps gpv group gsn gsnp gsv gu gv gwmi '\n 'h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp '\n 'ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv '\n 'oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo '\n 'rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc select '\n 'set shcm si sl sleep sls sort sp spjb spps spsv start sujb sv swmi tee '\n 'trcm type wget where wjb write').split()\n\n commenthelp = (\n 'component description example externalhelp forwardhelpcategory '\n 'forwardhelptargetname functionality inputs link '\n 'notes outputs parameter remotehelprunspace role synopsis').split()\n\n tokens = {\n 'root': [\n # we need to count pairs of parentheses for correct highlight\n # of '$(...)' blocks in strings\n (r'\\(', Punctuation, 'child'),\n (r'\\s+', Text),\n (r'^(\\s*#[#\\s]*)(\\.(?:%s))([^\\n]*$)' % '|'.join(commenthelp),\n bygroups(Comment, String.Doc, Comment)),\n (r'#[^\\n]*?$', Comment),\n (r'(<|<)#', Comment.Multiline, 'multline'),\n (r'@\"\\n', String.Heredoc, 'heredoc-double'),\n (r\"@'\\n.*?\\n'@\", String.Heredoc),\n # escaped syntax\n (r'`[\\'\"$@-]', Punctuation),\n (r'\"', String.Double, 'string'),\n (r\"'([^']|'')*'\", String.Single),\n (r'(\\$|@@|@)((global|script|private|env):)?\\w+',\n Name.Variable),\n (r'(%s)\\b' % '|'.join(keywords), Keyword),\n (r'-(%s)\\b' % '|'.join(operators), Operator),\n (r'(%s)-[a-z_]\\w*\\b' % '|'.join(verbs), Name.Builtin),\n (r'(%s)\\s' % '|'.join(aliases_), Name.Builtin),\n (r'\\[[a-z_\\[][\\w. `,\\[\\]]*\\]', Name.Constant), # .net [type]s\n (r'-[a-z_]\\w*', Name),\n (r'\\w+', Name),\n (r'[.,;:@{}\\[\\]$()=+*/\\\\&%!~?^`|<>-]', Punctuation),\n ],\n 'child': [\n (r'\\)', Punctuation, '#pop'),\n include('root'),\n ],\n 'multline': [\n (r'[^#&.]+', Comment.Multiline),\n (r'#(>|>)', Comment.Multiline, '#pop'),\n (r'\\.(%s)' % '|'.join(commenthelp), String.Doc),\n (r'[#&.]', Comment.Multiline),\n ],\n 'string': [\n (r\"`[0abfnrtv'\\\"$`]\", String.Escape),\n (r'[^$`\"]+', String.Double),\n (r'\\$\\(', Punctuation, 'child'),\n (r'\"\"', String.Double),\n (r'[`$]', String.Double),\n (r'\"', String.Double, '#pop'),\n ],\n 'heredoc-double': [\n (r'\\n\"@', String.Heredoc, '#pop'),\n (r'\\$\\(', Punctuation, 'child'),\n (r'[^@\\n]+\"]', String.Heredoc),\n (r\".\", String.Heredoc),\n ]\n }\n\n\nclass PowerShellSessionLexer(ShellSessionBaseLexer):\n \"\"\"\n Lexer for PowerShell sessions, i.e. command lines, including a\n prompt, interspersed with output.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'PowerShell Session'\n aliases = ['pwsh-session', 'ps1con']\n filenames = []\n mimetypes = []\n\n _innerLexerCls = PowerShellLexer\n _bare_continuation = True\n _ps1rgx = re.compile(r'^((?:\\[[^]]+\\]: )?PS[^>]*> ?)(.*\\n?)')\n _ps2 = '> '\n\n\nclass FishShellLexer(RegexLexer):\n \"\"\"\n Lexer for Fish shell scripts.\n\n .. versionadded:: 2.1\n \"\"\"\n\n name = 'Fish'\n aliases = ['fish', 'fishshell']\n filenames = ['*.fish', '*.load']\n mimetypes = ['application/x-fish']\n\n tokens = {\n 'root': [\n include('basic'),\n include('data'),\n include('interp'),\n ],\n 'interp': [\n (r'\\$\\(\\(', Keyword, 'math'),\n (r'\\(', Keyword, 'paren'),\n (r'\\$#?(\\w+|.)', Name.Variable),\n ],\n 'basic': [\n (r'\\b(begin|end|if|else|while|break|for|in|return|function|block|'\n r'case|continue|switch|not|and|or|set|echo|exit|pwd|true|false|'\n r'cd|count|test)(\\s*)\\b',\n bygroups(Keyword, Text)),\n (r'\\b(alias|bg|bind|breakpoint|builtin|command|commandline|'\n r'complete|contains|dirh|dirs|emit|eval|exec|fg|fish|fish_config|'\n r'fish_indent|fish_pager|fish_prompt|fish_right_prompt|'\n r'fish_update_completions|fishd|funced|funcsave|functions|help|'\n r'history|isatty|jobs|math|mimedb|nextd|open|popd|prevd|psub|'\n r'pushd|random|read|set_color|source|status|trap|type|ulimit|'\n r'umask|vared|fc|getopts|hash|kill|printf|time|wait)\\s*\\b(?!\\.)',\n Name.Builtin),\n (r'#.*\\n', Comment),\n (r'\\\\[\\w\\W]', String.Escape),\n (r'(\\b\\w+)(\\s*)(=)', bygroups(Name.Variable, Whitespace, Operator)),\n (r'[\\[\\]()=]', Operator),\n (r'<<-?\\s*(\\'?)\\\\?(\\w+)[\\w\\W]+?\\2', String),\n ],\n 'data': [\n (r'(?s)\\$?\"(\\\\\\\\|\\\\[0-7]+|\\\\.|[^\"\\\\$])*\"', String.Double),\n (r'\"', String.Double, 'string'),\n (r\"(?s)\\$'(\\\\\\\\|\\\\[0-7]+|\\\\.|[^'\\\\])*'\", String.Single),\n (r\"(?s)'.*?'\", String.Single),\n (r';', Punctuation),\n (r'&|\\||\\^|<|>', Operator),\n (r'\\s+', Text),\n (r'\\d+(?= |\\Z)', Number),\n (r'[^=\\s\\[\\]{}()$\"\\'`\\\\<&|;]+', Text),\n ],\n 'string': [\n (r'\"', String.Double, '#pop'),\n (r'(?s)(\\\\\\\\|\\\\[0-7]+|\\\\.|[^\"\\\\$])+', String.Double),\n include('interp'),\n ],\n 'paren': [\n (r'\\)', Keyword, '#pop'),\n include('root'),\n ],\n 'math': [\n (r'\\)\\)', Keyword, '#pop'),\n (r'[-+*/%^|&]|\\*\\*|\\|\\|', Operator),\n (r'\\d+#\\d+', Number),\n (r'\\d+#(?! )', Number),\n (r'\\d+', Number),\n include('root'),\n ],\n }\n\nclass ExeclineLexer(RegexLexer):\n \"\"\"\n Lexer for Laurent Bercot's execline language\n (https://skarnet.org/software/execline).\n\n .. versionadded:: 2.7\n \"\"\"\n\n name = 'execline'\n aliases = ['execline']\n filenames = ['*.exec']\n\n tokens = {\n 'root': [\n include('basic'),\n include('data'),\n include('interp')\n ],\n 'interp': [\n (r'\\$\\{', String.Interpol, 'curly'),\n (r'\\$[\\w@#]+', Name.Variable), # user variable\n (r'\\$', Text),\n ],\n 'basic': [\n (r'\\b(background|backtick|cd|define|dollarat|elgetopt|'\n r'elgetpositionals|elglob|emptyenv|envfile|exec|execlineb|'\n r'exit|export|fdblock|fdclose|fdmove|fdreserve|fdswap|'\n r'forbacktickx|foreground|forstdin|forx|getcwd|getpid|heredoc|'\n r'homeof|if|ifelse|ifte|ifthenelse|importas|loopwhilex|'\n r'multidefine|multisubstitute|pipeline|piperw|posix-cd|'\n r'redirfd|runblock|shift|trap|tryexec|umask|unexport|wait|'\n r'withstdinas)\\b', Name.Builtin),\n (r'\\A#!.+\\n', Comment.Hashbang),\n (r'#.*\\n', Comment.Single),\n (r'[{}]', Operator)\n ],\n 'data': [\n (r'(?s)\"(\\\\.|[^\"\\\\$])*\"', String.Double),\n (r'\"', String.Double, 'string'),\n (r'\\s+', Text),\n (r'[^\\s{}$\"\\\\]+', Text)\n ],\n 'string': [\n (r'\"', String.Double, '#pop'),\n (r'(?s)(\\\\\\\\|\\\\.|[^\"\\\\$])+', String.Double),\n include('interp'),\n ],\n 'curly': [\n (r'\\}', String.Interpol, '#pop'),\n (r'[\\w#@]+', Name.Variable),\n include('root')\n ]\n\n }\n\n def analyse_text(text):\n if shebang_matches(text, r'execlineb'):\n return 1\n","sub_path":"contrib/python/Pygments/py3/pygments/lexers/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":36466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"50537103","text":"import os\nimport xml.etree.ElementTree as EleTr\nimport graphviz as gviz\n\nfrom analysis.dict_functions import update_dict_occurences\nfrom analysis.question import question\n\n# Constants defining the color and arrow style for some tags\nNODE_TAGS = {\n 'PLACE': 'green',\n 'LOCATION': 'lightblue',\n 'SPATIAL_ENTITY': 'yellow',\n 'NONMOTION_EVENT': 'red',\n 'MOTION': 'purple',\n 'PATH': \"orange\"\n}\n\nEDGE_TAGS = {\n 'QSLINK': 'solid',\n 'OLINK': 'dashed'\n}\n\n\nclass FileAnalyzer:\n \"\"\"\n Handles the analysis of one file\n :param path: path of the file to be analyzed\n :param nlp: the NLP provided by spacy\n \"\"\"\n def __init__(self, path, nlp):\n # Sets variables\n self.path = path\n root = EleTr.parse(path).getroot()\n text = root.findall('TEXT')[0].text\n\n self.doc = nlp(text)\n self.tags = root.findall('TAGS')[0]\n self.pos_counter = self.create_pos_counter()\n self.sentences = [len(sent) for sent in self.doc.sents]\n\n def create_pos_counter(self):\n \"\"\"\n Creates a dictionary holding the distribution of all PoS-\n :return: dict: A dictionary of the PoS distribution\n \"\"\"\n pos_counter = {}\n for token in self.doc:\n update_dict_occurences(pos_counter, token.pos_)\n return pos_counter\n\n def get_pos_counter(self):\n \"\"\"\n :return: dict: A dictionary of the PoS distribution\n \"\"\"\n return self.pos_counter\n\n def get_tags(self):\n \"\"\"\n :return: The elment of the element-tree holding all tags\n \"\"\"\n return self.tags\n\n def get_sentences(self):\n \"\"\"\n :return: List of all sentence-lengths\n \"\"\"\n return self.sentences\n\n def visualize(self):\n \"\"\"\n Creates a Graph showing the relation between the different Tags\n \"\"\"\n file_name = self.path.split(os.sep)[-1][0:-4]\n print(f'--- {file_name} ---')\n\n graph = gviz.Digraph(comment=file_name, engine='circo')\n\n # Filters the tags in METALINK and non METALINK tags\n metalink_tags = [tag for tag in self.tags if tag.tag == 'METALINK']\n non_metalink_tags = [tag for tag in self.tags if tag.tag != 'METALINK']\n\n # Iterates over all Metalinks and merges two tags if necessary\n for tag in metalink_tags:\n from_id, to_id = tag.attrib['fromID'], tag.attrib['toID']\n non_metalink_tags = self.remove_and_replace(from_id, to_id, non_metalink_tags)\n\n # Filters the non METALINK tags in Nodes and Endges\n node_tags = [tag for tag in non_metalink_tags if tag.tag in NODE_TAGS]\n edge_tags = [tag for tag in non_metalink_tags if tag.tag in EDGE_TAGS]\n\n # Renders all Nodes\n for tag in node_tags:\n graph.node(name=tag.attrib['id'], label=tag.attrib['text'], fillcolor=NODE_TAGS[tag.tag], style='filled')\n\n # Renders all Edges\n for tag in edge_tags:\n graph.edge(tail_name=tag.attrib['fromID'], head_name=tag.attrib['toID'],\n label=tag.attrib['relType'], style=EDGE_TAGS[tag.tag], arrowhead='none')\n\n # Renders a legend explaining the colors and arrows\n label = '<
'\n for tag in NODE_TAGS:\n label += f'{tag} '\n label += 'QSLINK --- > OLINK - - - > '\n label += '
>'\n graph.attr(label=label)\n\n # Outputs the files\n save_location = os.path.join(__file__, '..', '..', 'results', 'graph')\n if not os.path.exists(save_location):\n os.makedirs(save_location)\n\n graph.render(os.path.join(save_location, f'{file_name}.gv'),\n view=question('Do you want to see the resulting graph?'))\n\n @staticmethod\n def remove_and_replace(old, new, tags):\n \"\"\"\n Updates the list of non_metalink_tags on a merge by updating the ids to the tag leftover and removing the\n merged 'old' tag.\n :param old: ID of the old tag\n :param new: ID of the new tag\n :param tags: List of all tags\n :return: list: List of updated tags\n \"\"\"\n for tag in tags:\n if tag.attrib['id'] == old:\n tags.remove(tag)\n elif 'fromID' in tag.attrib and tag.attrib['fromID'] == old:\n tag.attrib['fromID'] = new\n elif 'toID' in tag.attrib and tag.attrib['toID'] == old:\n tag.attrib['toID'] = new\n return tags\n","sub_path":"analysis/file_analyzer.py","file_name":"file_analyzer.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"204754727","text":"\r\nfrom numpy import exp\r\nimport sys\r\nsys.path.append('..\\pyfunctions')\r\nfrom numpy.random import seed\r\nseed(756)\r\nsys.path.append('..\\\\')\r\nfrom GetAgeFreq import GetAgeFreq\r\n\r\nfrom numpy import log\r\nfrom scipy.stats import linregress\r\n\r\ncsvfile='..\\\\TreeNobXdate.csv'\r\ncol=0#Use first column from file\r\nSurveyYear=2005\r\nMaxYear=1980\r\nMinYear=1980-52\r\n\r\n\r\ndata=GetAgeFreq(csvfile,col=col,SurveyYear=SurveyYear,MaxYear=MaxYear,MinYear=MinYear)\r\nnyear=len(data)\r\nna0=sum(data)\r\na0=0\r\nabar=sum([ i*data[i] for i in range(nyear)])/na0\r\n\r\nsCR=(abar-a0)/ ( (abar-a0) +(na0-1)/na0 )\r\nzCR=-log(sCR)\r\nzCRc=zCR- (na0-1)*(na0-2) / na0 / ( na0*(na0*(abar-a0)+1) ) / (na0 + na0*(na0*(abar-a0)-1) )\r\nzCRcSigma=((1-exp(-zCRc))**2)/na0/exp(-zCRc)\r\nprint(-2*zCRcSigma + zCRc ,0*zCRcSigma + zCRc ,+2*zCRcSigma + zCRc )","sub_path":"Traditional/EndChapmanRobson.py","file_name":"EndChapmanRobson.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"264542077","text":"\"\"\"GOPEM plotter.\"\"\"\nfrom __future__ import unicode_literals\nimport matplotlib\nfrom PyQt5 import QtWidgets\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nmatplotlib.use('Qt5Agg') # Make sure that we are using QT5\n\n\nclass MplCanvas(FigureCanvas):\n \"\"\"MplCanvas class.\"\"\"\n\n def __init__(self, parent=None, width=5, height=4, dpi=100):\n \"\"\"\n Initialize of MatPlotLib canvas for plotter.\n\n :param parent: the QWidget parent\n :param width: the initial width of canvas\n :param height: the initial height of canvas\n :param dpi: the dpi of the canvas\n \"\"\"\n fig = Figure(figsize=(width, height), dpi=dpi)\n self.axes = fig.add_subplot(111)\n\n FigureCanvas.__init__(self, fig)\n self.setParent(parent)\n\n FigureCanvas.setSizePolicy(self,\n QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n\n def update_plot(self, data, x_axis, y_axis):\n \"\"\"\n Update the data and axis range of the canvas.\n\n :param data: a dictionary that contains the data points\n :param x_axis: the ticks on X axis\n :param y_axis: the ticks on Y axis\n :return: None\n \"\"\"\n self.axes.cla()\n self.axes.grid(True, linestyle='-.', which='both')\n if x_axis in data.keys() and y_axis in data.keys():\n self.axes.plot(data[x_axis], data[y_axis], 'r')\n self.axes.set_xlabel(x_axis)\n self.axes.set_ylabel(y_axis)\n\n self.draw()\n\n\nclass ApplicationWindow(QtWidgets.QWidget):\n \"\"\"ApplicationWindow class.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Application widget for MPLCanvas class.\n\n :param args: the list of arguments\n :param kwargs: the dictionary of keywords\n \"\"\"\n super().__init__(*args, **kwargs)\n self.setMinimumSize(400, 400)\n l = QtWidgets.QVBoxLayout(self)\n self.sc = MplCanvas(self, width=20, height=20, dpi=100)\n\n l.addWidget(self.sc)\n\n def update_plotter_data(self, data, x_axis, y_axis):\n \"\"\"\n Update the plotter data and axis.\n\n :param data: the dictionary of data\n :param x_axis: the Ticks on X axis\n :param y_axis: the Ticks on Y axis\n :return: None\n \"\"\"\n self.sc.update_plot(data, x_axis, y_axis)\n\n def file_quit(self):\n \"\"\"\n Close the application.\n\n :return: None\n \"\"\"\n self.close()\n\n def close_event(self, ce):\n \"\"\"\n Slot for close event trigger.\n\n :param ce: close event\n :return: None\n \"\"\"\n self.file_quit()\n","sub_path":"gopem/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"58029490","text":"#Brian Wong 34216498 Project 4 ICS 32 Lab 13\n\nNONE = ' '\nWHITE = 'O'\nBLACK = 'X'\n\ndef opposite_color(color: str) -> str:\n \"\"\"changes the color\"\"\"\n if color == BLACK:\n return WHITE\n else:\n return BLACK\n\n \nfrom collections import namedtuple\nLocation = namedtuple('Location', ['col', 'row'])\n\n\n\nclass Piece:\n def __init__(self, color: str, col: int, row: int):\n \"\"\"Initializes Piece to have a col, row, and color\"\"\"\n self._color = color\n self._col = col\n self._row = row\n\n def get_row(self) -> int:\n \"\"\"gets the # of rows\"\"\"\n return self._row\n\n def get_col(self) -> int:\n \"\"\"gets the # of cols\"\"\"\n return self._col\n\n def get_color(self) -> str:\n \"\"\"Returns color of this Piece\"\"\"\n return self._color\n\n def flipper(self):\n \"\"\"flips the color of the pieces\"\"\"\n if self._color == WHITE:\n self._color = BLACK\n else:\n self._color = WHITE\n \n\n\n\nclass Board:\n def __init__(self, cols: int, rows:int, top_left_pos: str):\n \"\"\"Initializes Board to have a col, row, and color\"\"\"\n if (cols%2==0 and cols>=4 and cols<=16 and rows%2==0\n and rows>=4 and rows<=16):\n self._col = cols\n self._row = rows\n self._board = self.board() #saves board changes\n self.starting_positions(top_left_pos)\n else:\n raise ValueError() #handle error in UI, ask user again\n\n def get_columns(self):\n \"\"\"gets column number\"\"\"\n return self._col\n\n def get_rows(self):\n \"\"\"gets row number\"\"\"\n return self._row\n\n def get_board(self):\n \"\"\"get board\"\"\"\n return self._board\n \n def board(self)->list:\n \"\"\"Creates new board\"\"\"\n \n board = []\n for i in range(self._col):\n row = []\n for j in range(self._row):\n row.append(NONE)\n board.append(row)\n return board\n\n def starting_positions(self, top_left_pos:str):\n \"\"\"drops pieces in starting locations\"\"\"\n if top_left_pos == BLACK:\n opposite_color = WHITE\n else:\n opposite_color = BLACK\n x = int(self._col/2)\n y = int(self._row/2)\n self.drop_on_board(x-1, y-1, top_left_pos)\n self.drop_on_board(x, y, top_left_pos)\n self.drop_on_board(x, y-1, opposite_color)\n self.drop_on_board(x-1, y, opposite_color)\n \n\n def drop_on_board(self, col: int, row: int, color: str):\n \"\"\"Puts a piece on the board, checks if it fits on the board, but\n not if its a valid Othello move\"\"\"\n self._board[col][row] = Piece(color, col, row)\n\n def print_board(self) -> None:\n \"\"\"\n Prints the current state of the board\n \"\"\"\n board = self._board\n print(' ', end=' ')\n for i in range(len(board)):\n print('{:2d}'.format(i+1), end = ' ') \n print()\n\n for row in range(self._row):\n print('{:2d}'.format(row+1), end= ' ')\n for col in range(self._col):\n box = board[col][row] \n if(box == NONE):\n print('{:2s}'.format('.'), end=' ')\n else:\n print('{:2s}'.format(box.get_color()), end=' ')\n print()\n\n \n \n\nclass Game:\n def __init__(self, board_cols:int, board_rows: int,\n color:str, top_left_pos:str):\n self._cols = board_cols\n self._rows = board_rows\n self._board = Board(board_cols, board_rows, top_left_pos)\n self._current_player = color\n\n def get_current_player(self):\n \"\"\"gets current player\"\"\"\n return self._current_player\n\n def test_drop_valid_piece(self, drop_col: int, drop_row: int, color: str) ->list:\n \"\"\"\n Test for valid drops\n #1 Test if its valid to drop the piece in that place\n \"\"\"\n pieces = []\n directions = ['right', 'left', 'top', 'bottom', 'top_right', 'top_left', 'bottom_right', 'bottom_left']\n for direction in directions:\n pieces.extend(self.flip_each_direction(drop_col, drop_row, color, direction))\n return pieces\n \n\n def drop_valid_piece(self, drop_col: int, drop_row:int):\n \"\"\"\n Test for valid drops\n #1 flip the pieces that need to be flipped\n #2 drop the piece\n \"\"\"\n pieces = self.test_drop_valid_piece(drop_col,drop_row,self._current_player)\n \n if len(pieces) != 0:\n for piece in pieces:\n piece.flipper()\n self._board.drop_on_board(drop_col, drop_row, self._current_player)\n self.flips_no_moves()\n else:\n raise ValueError()\n\n \n\n def flip_each_direction(self, starting_col: int, starting_row: int, color: str, direction: str) ->list:\n \"\"\"Find flippable pieces in each direction, returns list of coordinates in that direction\"\"\"\n flippable_pieces = []\n loop_count = 0\n i = starting_col\n j = starting_row\n valid = False\n while True:\n if i == starting_col and j == starting_row:\n piece = self._board.get_board()[i][j]\n if type(piece)== Piece:\n break\n elif i != starting_col or j != starting_row:\n piece = self._board.get_board()[i][j]\n if type(piece) == str: ##is empty\n break\n elif loop_count == 1: ## piece next to starting point\n if piece.get_color() == color:\n break\n elif piece.get_color() == color:\n valid = True\n break\n\n flippable_pieces.append(piece)\n\n if direction == 'right':\n if i == self._cols-1:\n break\n i +=1\n elif direction == 'left':\n if i == 0:\n break\n i -= 1\n elif direction == 'top':\n if j == 0:\n break\n j -= 1\n elif direction == 'bottom':\n if j == self._rows-1:\n break\n j += 1\n elif direction == 'top_right':\n if i == self._cols-1 or j == 0:\n break\n i += 1\n j -= 1\n elif direction == 'top_left':\n if i == 0 or j == 0:\n break\n i -= 1\n j -= 1\n elif direction == 'bottom_right':\n if i == self._cols-1 or j == self._rows-1:\n break\n i += 1\n j += 1\n elif direction == 'bottom_left':\n if i == 0 or j == self._rows - 1:\n break\n i -= 1\n j += 1\n\n loop_count += 1\n \n if valid:\n return flippable_pieces\n else:\n return []\n \n \n ## 1.) if the FIRST spot has a piece that is the opposite color, then can keep going \n ## 2.) if blank, it means it cant be valid even. if not, keep going\n ## 3.) if you hit a piece after the first one that is your color, it's a valid move\n \n\n def num_white_piece(self):\n \"\"\"counts number of white pieces\"\"\"\n count = 0\n for column in self._board.get_board():\n for cell in column:\n if type(cell) == Piece and cell.get_color() == WHITE:\n count +=1\n return count \n\n def num_black_piece(self):\n \"\"\"counts number of black pieces\"\"\"\n count = 0\n for column in self._board.get_board():\n for cell in column:\n if type(cell) == Piece and cell.get_color() == BLACK:\n count +=1\n return count\n\n def opposite_turn(self):\n \"\"\"given the player whose turn it is now, return the opposite player\"\"\"\n self._current_player = opposite_color(self._current_player)\n\n \n def list_of_valid_moves(self, color: str):\n \"\"\"Returns a list of valid moves that a player has\"\"\"\n valid = []\n for col in range(self._cols):\n for row in range(self._rows):\n if type(self._board.get_board()[col][row]) == str:\n flippable_pieces = self.test_drop_valid_piece(col, row, color)\n if len(flippable_pieces) != 0:\n valid.append(Location(col=col+1, row=row+1))\n return valid\n\n def flips_no_moves(self):\n \"\"\"If the player has no more moves, flip to the next player.\n If the new player has no more moves end game(throw error).\"\"\"\n current_player_moves = self.list_of_valid_moves(self._current_player)\n next_color = opposite_color(self._current_player)\n opposite_player_moves = self.list_of_valid_moves(next_color)\n\n if len(opposite_player_moves) != 0:\n self.opposite_turn()\n elif len(opposite_player_moves) == 0 and len(current_player_moves) == 0:\n ## both players can't move; game over\n raise GameOverError()\n\nclass GameOverError(Exception):\n pass\n \n \n\n \n\n\n","sub_path":"othello_logic.py","file_name":"othello_logic.py","file_ext":"py","file_size_in_byte":9413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"82052363","text":"##script used to parse PCC motif matrix to sig or not sig\nimport os, sys\n\nsum_matrix = open(sys.argv[1],\"r\") #miteupLMup_TFBM_TFfamily_Low_PCC_average.txt\noutput = open(sys.argv[1] + \"_sig.txt\", \"w\")\n\n\nD = {}\ndef add_data_to_dict(inp):\n for line in inp:\n if line.startswith(\"#python\"):\n pass\n if line.startswith(\"motif\"):\n L = line.strip().split(\"\\t\")\n title_list = L[0:]\n title_str = '\\t'.join(title_list)\n output.write(title_str + '\\n')\n else:\n L2 = line.strip().split('\\t')\n motif = L2[0]\n PCC_dist = L2[1:]\n sig_list= []\n for dist in PCC_dist:\n if float(dist) <=0.39:\n sig_list.append(str(1))\n else:\n sig_list.append(str(0))\n sig_str = \"\\t\".join(sig_list)\n output.write('%s\\t%s\\n' % (motif, sig_str))\n\nadd_data_to_dict(sum_matrix)\n\noutput.close()","sub_path":"convert_sig_motif2.py","file_name":"convert_sig_motif2.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"82968758","text":"def fibonacci(n):\r\n if n <= 1:\r\n return n\r\n else:\r\n return fibonacci(n - 1) + fibonacci(n - 2)\r\n\r\n# T(n) = T(n-1) + T(n-2)\r\n# T(n) = 2*T(n-1)\r\n# T(n) = O(2*T(n-1) O definition\r\n# T(n) = O(2^(n-1)) product rule\r\n# T(n) = O(2^n) sum rule\r\n# ____________+\r\n# O(2^n)\r\n\r\nprint(fibonacci(8))\r\n","sub_path":"talleres/taller04/Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"304315937","text":"import re\n\nimport argparse\n\nfrom common import execute_command, env\nfrom git import git_command, has_git_changes\nfrom github import add_assignee, get_branch, create_pull_request\n\nCHECK_WORKFLOW_PATH = \".github/workflows/check.yml\"\nRUSTC_VERSION_RE = re.compile(r\".* \\(\\w*\\s*(\\d{4}-\\d{2}-\\d{2})\\)\")\nWORKFLOW_RUSTC_VERSION_RE = re.compile(r\"(rust-version: \\[.*nightly-)\\d{4}-\\d{2}-\\d{2}(.*])\")\nNIGHTLY_BRANCH = \"nightly\"\nDEFAULT_ASSIGNEE = \"Undin\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--token\", type=str, required=True, help=\"github token\")\n\n args = parser.parse_args()\n\n repo = env(\"GITHUB_REPOSITORY\")\n\n nightly_branch = get_branch(repo, args.token, NIGHTLY_BRANCH)\n if nightly_branch is not None:\n print(\"Repo already has nightly branch\")\n return\n\n git_command(\"checkout\", \"-b\", NIGHTLY_BRANCH)\n\n output = execute_command(\"rustc\", \"-V\")\n match_result = RUSTC_VERSION_RE.match(output)\n date = match_result.group(1)\n with open(CHECK_WORKFLOW_PATH) as f:\n workflow_text = f.read()\n\n result = re.search(WORKFLOW_RUSTC_VERSION_RE, workflow_text)\n if result is None:\n raise ValueError(\"Failed to find the current version of nightly rust\")\n\n new_workflow_text = re.sub(WORKFLOW_RUSTC_VERSION_RE, f\"\\\\g<1>{date}\\\\g<2>\", workflow_text)\n if new_workflow_text == workflow_text:\n print(\"The latest nightly rustc version is already used\")\n return\n\n with open(CHECK_WORKFLOW_PATH, \"w\") as f:\n f.write(new_workflow_text)\n\n if has_git_changes():\n git_command(\"add\", CHECK_WORKFLOW_PATH)\n git_command(\"commit\", \"-m\", \":arrow_up: nightly\")\n\n git_command(\"push\", \"origin\", NIGHTLY_BRANCH)\n pull_request = create_pull_request(repo, args.token, NIGHTLY_BRANCH, \":arrow_up: nightly\")\n add_assignee(repo, args.token, pull_request[\"number\"], DEFAULT_ASSIGNEE)\n else:\n print(\"Everything is up to date\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/update_nightly.py","file_name":"update_nightly.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"173357271","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport csv\nimport json\nimport logging\nimport sys\nimport urllib\nimport urllib2\nfrom time import gmtime, strftime\n\n# python2 to handle utf8 string\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nAPI_CALL_LIMIT = 50\n\n\ndef retrieve_name_gender(first_name):\n url = \"https://api.genderize.io/?name=\" + first_name\n try:\n res = urllib2.urlopen(url)\n if res:\n json_res = json.load(res)\n logging.root.debug(first_name + \"'s results are \" + str(json_res))\n return json_res\n except Exception as e:\n logging.root.warn(e)\n return None\n\n return None\n\n\ndef main():\n # parse arguments\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-n', '--name_list', required=True,\n help='name_list with frequency')\n parser.add_argument('-i', '--input', required=True,\n help='existed name_gender_file')\n parser.add_argument('-o', '--output', required=True,\n help='output name_gender_file')\n parser.add_argument('-c', '--number_of_scraping', required=True,\n help='number of names to be scraped')\n parser.add_argument('-l', '--logging', required=False,\n help='logging level')\n\n args = parser.parse_args()\n log_handler = logging.StreamHandler()\n log_formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s - %(message)s')\n log_handler.setFormatter(log_formatter)\n logging.root.addHandler(log_handler)\n logging.root.setLevel(level=logging.INFO)\n if args.logging and args.logging.lower() == \"debug\":\n logging.root.setLevel(level=logging.DEBUG)\n\n input_file = args.input\n output_file = args.output\n name_file = args.name_list\n number = args.number_of_scraping\n\n name_list = []\n with open(name_file) as name_input_file:\n name_input_data = csv.DictReader(name_input_file)\n for row in name_input_data:\n first_name = row[\"first_name\"].lower().strip()\n freq = row[\"freq\"]\n if first_name and freq and freq > 0:\n entry = {\n \"first_name\": first_name,\n \"index_freq\": freq\n }\n name_list.append(entry)\n\n logging.root.info(\"read \" + str(len(name_list)) + \" name entries from \" + name_file + \".\")\n\n # read from existed list\n name_gender_dict = {}\n with open(input_file) as name_gender_input_file:\n name_gender_input_data = csv.DictReader(name_gender_input_file)\n for row in name_gender_input_data:\n name = row[\"First_name\"].lower().strip()\n if name and name not in name_gender_dict:\n name_gender_dict[name] = {\n \"index_freq\": row[\"Index_freq\"],\n \"gender\": row[\"Gender\"],\n \"probability\": row[\"Probability\"],\n \"updated\": row[\"Updated\"]\n }\n else:\n logging.root.warn(str(name) + \" is either none or duplicates\")\n logging.root.info(\"read \" + str(len(name_gender_dict)) + \" existed name gender entries from \" + input_file + \".\")\n\n # API_CALL_LIMIT\n count = 0\n for name_entry in name_list:\n first_name = name_entry[\"first_name\"]\n freq = name_entry[\"index_freq\"]\n if first_name in name_gender_dict:\n if freq != name_gender_dict[first_name][\"index_freq\"]:\n name_gender_dict[first_name][\"index_freq\"] = freq\n else:\n count += 1\n try:\n res = retrieve_name_gender(first_name)\n except Exception as e:\n logging.root.warn(e)\n break\n if not res:\n logging.root.error(first_name + \" API call result is None\")\n break\n if \"name\" in res and \"gender\" in res and \"probability\" in res:\n name_gender_dict[first_name] = {\n \"index_freq\": freq,\n \"gender\": res[\"gender\"],\n \"probability\": res[\"probability\"],\n \"updated\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n }\n else:\n logging.root.warn(\"API call return result does not have all keys: \" + str(res))\n name_gender_dict[first_name] = {\n \"index_freq\": freq,\n \"gender\": \"any\",\n \"probability\": 1,\n \"updated\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n }\n if count > number:\n break\n logging.root.info(\"call API \" + str(count) + \" times\")\n logging.root.info(\"name_gender_dict has \" + str(len(name_gender_dict)) + \" entries now.\")\n\n # write results back to csv file\n with open(output_file, \"w\") as output_csv_file:\n fieldnames = [\"First_name\", \"Index_freq\", \"Gender\", \"Probability\", \"Updated\"]\n writer = csv.DictWriter(output_csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for first_name in sorted(name_gender_dict.iterkeys()):\n writer.writerow({\"First_name\": first_name,\n \"Index_freq\": name_gender_dict[first_name][\"index_freq\"],\n \"Gender\": name_gender_dict[first_name][\"gender\"],\n \"Probability\": name_gender_dict[first_name][\"probability\"],\n \"Updated\": name_gender_dict[first_name][\"updated\"]\n })\n logging.root.info(\"write \" + str(len(name_gender_dict)) + \" name gender entries to \" + output_file + \".\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cele_tools/retrieve_name_gender.py","file_name":"retrieve_name_gender.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"325835643","text":"#Exercio capitulo 2 programa 2 18/10/2018\n\narea = int(input(\"Entre com aréa a pintar: \"))\n\nlitros = area // 3 # divisao inteira \n \nif area % 3 > 0 :\n litros = litros + 1\n \nprint(litros) \n \n\n","sub_path":"Fund_Python_2018/Exercicos/Cap_2_Prog_2.py","file_name":"Cap_2_Prog_2.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"215829594","text":"import hashlib\nfrom tkinter import *\nimport argparse\n\nclass BaseMethod:\n def __init__(self):\n self.sessions = {'3.2': ['2 - Logging',\n '3 - Graphics'],\n '6.2': ['2 - Pokemon',\n '3 - Crypto Exchange', \n '4 - What3words',\n '5 - Flying Aircraft']}\n self.user_email = ''\n self.sessions_key = ''\n\n def user_input_output(self):\n '''\n Method for gathering both user email and session user is querying.\n '''\n pass\n\n def problem_choice(self, sessions_key, email):\n '''\n Method for determining the session given the student's email. This is standard throughout\n all implementations so useful to implement in abstract class.\n '''\n email = self.user_email.strip().lower() #xtra careful\n sessions_key = self.sessions_key.strip().lower() #xtra careful\n enc = (email + sessions_key).encode()\n md5 = hashlib.md5(enc).hexdigest()\n ind = int(md5, 16) % len(self.sessions[sessions_key])\n return self.sessions[sessions_key][ind]\n\n def run_main_program(self):\n '''\n Function for inherited class specific implementation to work.\n '''\n self.user_input_output()\n\nclass Terminal(BaseMethod):\n def __init__(self):\n super().__init__()\n\n def user_input_output(self):\n self.user_email = input(\"Please enter your student email address: \")\n while \"@minerva.kgi.edu\" not in self.user_email:\n print(\"Oops, I don't think that's a Minervan email address, would you mind checking you typed it write? You wrote {}.\".format(self.user_email))\n self.user_email = input(\"Please enter your student email address: \")\n\n self.sessions_key = input(\"What session is this for (sessions supported: {}): \".format(\", \".join([*self.sessions])))\n while self.sessions_key not in self.sessions.keys():\n print(\"Oops, I don't think we support that session number, would you mind checking you typed it write? You wrote {}.\".format(self.sessions_key))\n self.sessions_key = input(\"What session is this for (sessions supported: {}): \".format(\", \".join([*self.sessions])))\n\n print(\"You'll be doing: {}.\".format(self.problem_choice(self.sessions_key, self.user_email)))\n\nclass TKinter(BaseMethod):\n def __init__(self):\n super().__init__()\n\n def user_input_output(self):\n top = Toplevel(self.root)\n label_user_email = Label(top, text=\"Please enter your student email address:\")\n label_user_email.pack()\n entry_user_email = Entry(top)\n entry_user_email.pack()\n label_sessions_key = Label(top, text=\"Which Session is this for?\")\n label_sessions_key.pack()\n entry_sessions_key = Entry(top)\n entry_sessions_key.pack()\n\n def checker():\n self.user_email = entry_user_email.get()\n self.sessions_key = entry_sessions_key.get()\n if \"@minerva.kgi.edu\" in self.user_email and self.sessions_key in [*self.sessions]:\n top.destroy()\n display_selection()\n else:\n if \"@minerva.kgi.edu\" in self.user_email:\n label_warning = Label(top, text=\"It looks like you may not have entered a session we currently support!\\n Would you mind retyping? As a reminder, you wrote {}.\\n We currently only support ({})\".format(self.sessions_key, \", \".join([*self.sessions])))\n else:\n label_warning = Label(top, text=\"Would you mind checking you entered a minerva address?\\n As a reminder, you wrote {}.\".format(self.user_email))\n\n label_warning.pack()\n\n if hasattr(self.root, 'label_warning'):\n self.user_input()\n\n b = Button(top, text='Submit', command=checker)\n b.pack()\n top.attributes(\"-topmost\", True)\n\n def display_selection():\n self.root.title(\"Pre-Class Work Select\")\n self.root.geometry(\"300x100\")\n Label(self.root, text='For seminar {}'.format(self.sessions_key)).pack()\n Label(self.root, text=self.problem_choice(self.sessions_key, self.user_email)).pack()\n\n def run_main_program(self):\n self.root = Tk()\n self.user_input_output()\n self.root.mainloop()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='UI Controller')\n\n parser.add_argument('UI', action='store', default=Terminal)\n\n args = parser.parse_args()\n\n methods = {\n 'TKinter' : TKinter(),\n 'Terminal' : Terminal()\n }\n\n try:\n methods[vars(args)['UI']].run_main_program()\n except KeyError:\n print(\"Oops, I don't recognize that UI. Want to implement it?\")\n","sub_path":"utils/pcw_selector.py","file_name":"pcw_selector.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"336785069","text":"import pygame\nfrom pygame.sprite import Sprite\nfrom timer import Timer\n\n\nclass Koopa(Sprite):\n def __init__(self, screen):\n super(Koopa, self).__init__()\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.image = pygame.image.load('images/minion/koopa-1.png')\n self.rect = self.image.get_rect()\n self.rect.x = self.rect.width\n self.rect.y = self.rect.height\n self.x = float(self.rect.x)\n\n frames = [pygame.image.load('images/minion/koopa-1.png'),\n pygame.image.load('images/minion/koopa-2.png')]\n self.koopa_moving_timer = Timer(frames)\n\n self.is_dead = False\n self.speed_factor = 1\n self.direction = -1 # -1 = left\n\n def update(self):\n self.x += (self.speed_factor * self.direction)\n self.rect.x = self.x\n\n def blitme(self):\n self.screen.blit(self.image, self.rect)","sub_path":"goomba.py","file_name":"goomba.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"426426080","text":"def mean(vals):\n\t\"\"\"Calculate the arithmetic mean of a list of numbers in vals\"\"\"\n\tassert type(vals) is list, \"wrong input format\"\n\t\n\ttotal = sum(vals)\n\tlength = len(vals)\n\tif length == 0:\n\t\treturn 0.0\n\telse:\n\t\treturn total/length\n\t\n#potential problems: empty list; data types; test cases\n\n#print(mean(\"hello\"))\n\n\n\n","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"554303528","text":"\"\"\"\nCopyright (c) 2017 Red Hat, Inc\nAll rights reserved.\n\nThis software may be modified and distributed under the terms\nof the BSD license. See the LICENSE file for details.\n\"\"\"\n\nfrom atomic_reactor.core import DockerTasker\nfrom atomic_reactor.inner import DockerBuildWorkflow\nfrom atomic_reactor.plugin import BuildCanceledException, PluginFailedException\nfrom atomic_reactor.plugin import BuildStepPluginsRunner\nfrom atomic_reactor.plugins import pre_reactor_config\nfrom atomic_reactor.plugins.build_orchestrate_build import (OrchestrateBuildPlugin,\n get_worker_build_info,\n get_koji_upload_dir,\n override_build_kwarg)\nfrom atomic_reactor.plugins.pre_reactor_config import (ReactorConfig,\n ReactorConfigPlugin,\n WORKSPACE_CONF_KEY)\nfrom atomic_reactor.plugins.pre_check_and_set_rebuild import CheckAndSetRebuildPlugin\nfrom atomic_reactor.util import df_parser\nimport atomic_reactor.util\nfrom atomic_reactor.constants import (PLUGIN_ADD_FILESYSTEM_KEY,\n PLUGIN_CHECK_AND_SET_PLATFORMS_KEY)\nfrom flexmock import flexmock\nfrom multiprocessing.pool import AsyncResult\nfrom osbs.api import OSBS\nfrom osbs.conf import Configuration\nfrom osbs.build.build_response import BuildResponse\nfrom osbs.exceptions import OsbsException\nfrom osbs.core import Openshift\nfrom osbs.utils import ImageName\nfrom tests.constants import MOCK_SOURCE, INPUT_IMAGE, SOURCE\nfrom tests.docker_mock import mock_docker\nfrom tests.util import add_koji_map_in_workflow\nfrom textwrap import dedent\nfrom copy import deepcopy\n\nimport json\nimport os\nimport sys\nimport pytest\nimport time\nimport platform\n\n\nMANIFEST_LIST = {\n 'manifests': [\n {'platform': {'architecture': 'amd64'}, 'digest': 'sha256:123456'},\n {'platform': {'architecture': 'ppc64le'}, 'digest': 'sha256:123456'},\n ]\n}\n\n\nDEFAULT_CLUSTERS = {\n 'x86_64': [\n {\n 'name': 'worker_x86_64',\n 'max_concurrent_builds': 3\n }\n ],\n 'ppc64le': [\n {\n 'name': 'worker_ppc64le',\n 'max_concurrent_builds': 3\n }\n ]\n}\n\n\nclass MockSource(object):\n\n def __init__(self, tmpdir):\n tmpdir = str(tmpdir)\n self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile')\n self.path = tmpdir\n self.config = flexmock(image_build_method=None)\n\n def get_build_file_path(self):\n return self.dockerfile_path, self.path\n\n\nclass MockInsideBuilder(object):\n\n def __init__(self):\n mock_docker()\n self.tasker = DockerTasker()\n self.base_image = ImageName(repo='fedora', tag='25')\n self.image_id = 'image_id'\n self.image = INPUT_IMAGE\n self.df_path = 'df_path'\n self.df_dir = 'df_dir'\n self.parent_images_digests = {}\n\n def simplegen(x, y):\n yield \"some\\u2018\".encode('utf-8')\n flexmock(self.tasker, build_image_from_path=simplegen)\n\n def get_built_image_info(self):\n return {'Id': 'some'}\n\n def inspect_built_image(self):\n return None\n\n def ensure_not_built(self):\n pass\n\n\nclass fake_imagestream_tag(object):\n def __init__(self, json_cont):\n self.json_cont = json_cont\n\n def json(self):\n return self.json_cont\n\n\nclass fake_manifest_list(object):\n def __init__(self, json_cont):\n self.content = json_cont\n\n def json(self):\n return self.content\n\n\npytestmark = pytest.mark.usefixtures('user_params')\n\n\ndef mock_workflow(tmpdir, platforms=None):\n workflow = DockerBuildWorkflow(source=MOCK_SOURCE)\n builder = MockInsideBuilder()\n source = MockSource(tmpdir)\n setattr(builder, 'source', source)\n setattr(workflow, 'source', source)\n setattr(workflow, 'builder', builder)\n\n df_path = os.path.join(str(tmpdir), 'Dockerfile')\n with open(df_path, 'w') as f:\n f.write(dedent(\"\"\"\\\n FROM fedora:25\n LABEL com.redhat.component=python \\\n version=2.7 \\\n release=10\n \"\"\"))\n df = df_parser(df_path)\n setattr(workflow.builder, 'df_path', df.dockerfile_path)\n\n platforms = ['x86_64', 'ppc64le'] if platforms is None else platforms\n workflow.prebuild_results[PLUGIN_CHECK_AND_SET_PLATFORMS_KEY] = set(platforms)\n\n build = {\n \"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/some_image@sha256:123456\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"name\": \"registry/some_image:latest\",\n \"kind\": \"DockerImage\"})}}}\n flexmock(os, environ={'BUILD': json.dumps(build)})\n\n return workflow\n\n\ndef mock_reactor_config(tmpdir, clusters=None, empty=False, add_config=None):\n if not clusters and not empty:\n clusters = deepcopy(DEFAULT_CLUSTERS)\n\n koji_map = {\n 'hub_url': '/',\n 'root_url': '',\n 'auth': {}\n }\n\n conf_json = {\n 'version': 1,\n 'clusters': clusters,\n 'koji': koji_map\n }\n if add_config:\n conf_json.update(add_config)\n conf = ReactorConfig(conf_json)\n (flexmock(pre_reactor_config)\n .should_receive('get_config')\n .and_return(conf))\n\n with open(os.path.join(str(tmpdir), 'osbs.conf'), 'w') as f:\n for plat_clusters in clusters.values():\n for cluster in plat_clusters:\n f.write(dedent(\"\"\"\\\n [{name}]\n openshift_url = https://{name}.com/\n namespace = {name}_namespace\n \"\"\".format(name=cluster['name'])))\n return conf_json\n\n\ndef mock_manifest_list():\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(fake_manifest_list(MANIFEST_LIST)))\n\n\ndef mock_orchestrator_platfrom(plat='x86_64'):\n (flexmock(platform)\n .should_receive('processor')\n .and_return(plat))\n\n\ndef mock_osbs(current_builds=2, worker_builds=1, logs_return_bytes=False, worker_expect=None):\n (flexmock(OSBS)\n .should_receive('list_builds')\n .and_return(list(range(current_builds))))\n\n koji_upload_dirs = set()\n\n def mock_create_worker_build(**kwargs):\n # koji_upload_dir parameter must be identical for all workers\n koji_upload_dirs.add(kwargs.get('koji_upload_dir'))\n assert len(koji_upload_dirs) == 1\n\n if worker_expect:\n testkwargs = deepcopy(kwargs)\n testkwargs.pop('koji_upload_dir')\n assert testkwargs == worker_expect\n\n return make_build_response('worker-build-{}'.format(kwargs['platform']),\n 'Running')\n (flexmock(OSBS)\n .should_receive('create_worker_build')\n .replace_with(mock_create_worker_build))\n\n if logs_return_bytes:\n log_format_string = b'line \\xe2\\x80\\x98 - %d'\n else:\n log_format_string = 'line \\u2018 - %d'\n\n (flexmock(OSBS)\n .should_receive('get_build_logs')\n .and_yield(log_format_string % line for line in range(10)))\n\n def mock_wait_for_build_to_finish(build_name):\n return make_build_response(build_name, 'Complete')\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n\n\ndef make_build_response(name, status, annotations=None, labels=None):\n build_response = {\n 'metadata': {\n 'name': name,\n 'annotations': annotations or {},\n 'labels': labels or {},\n },\n 'status': {\n 'phase': status\n }\n }\n\n return BuildResponse(build_response)\n\n\ndef make_worker_build_kwargs(**overrides):\n kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'arrangement_version': 6\n }\n kwargs.update(overrides)\n return kwargs\n\n\ndef teardown_function(function):\n sys.modules.pop('build_orchestrate_build', None)\n\n\n@pytest.mark.parametrize('config_kwargs', [\n None,\n {},\n {'build_image': 'osbs-buildroot:latest'},\n {'build_image': 'osbs-buildroot:latest', 'sources_command': 'fedpkg source'},\n {'build_image': 'osbs-buildroot:latest',\n 'equal_labels': 'label1:label2,label3:label4'},\n])\n@pytest.mark.parametrize('worker_build_image', [\n 'fedora:latest',\n None\n])\n@pytest.mark.parametrize('logs_return_bytes', [\n True,\n False\n])\ndef test_orchestrate_build(tmpdir, caplog,\n config_kwargs, worker_build_image, logs_return_bytes):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs(logs_return_bytes=logs_return_bytes)\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n }\n if worker_build_image:\n plugin_args['worker_build_image'] = worker_build_image\n if config_kwargs is not None:\n plugin_args['config_kwargs'] = config_kwargs\n\n expected_kwargs = {\n 'conf_section': str('worker_x86_64'),\n 'conf_file': str(tmpdir) + '/osbs.conf',\n 'sources_command': None,\n 'koji_hub': '/',\n 'koji_root': ''\n }\n if config_kwargs:\n expected_kwargs['sources_command'] = config_kwargs.get('sources_command')\n if 'equal_labels' in config_kwargs:\n expected_kwargs['equal_labels'] = config_kwargs.get('equal_labels')\n\n clusters = deepcopy(DEFAULT_CLUSTERS)\n\n reactor_dict = {'version': 1, 'arrangement_version': 6}\n if config_kwargs and 'sources_command' in config_kwargs:\n reactor_dict['sources_command'] = 'fedpkg source'\n\n expected_kwargs['source_registry_uri'] = None\n reactor_dict['odcs'] = {'api_url': 'odcs_url'}\n expected_kwargs['odcs_insecure'] = False\n expected_kwargs['odcs_url'] = reactor_dict['odcs']['api_url']\n reactor_dict['prefer_schema1_digest'] = False\n expected_kwargs['prefer_schema1_digest'] = reactor_dict['prefer_schema1_digest']\n reactor_dict['smtp'] = {\n 'from_address': 'from',\n 'host': 'smtp host'}\n expected_kwargs['smtp_host'] = reactor_dict['smtp']['host']\n expected_kwargs['smtp_from'] = reactor_dict['smtp']['from_address']\n expected_kwargs['smtp_email_domain'] = None\n expected_kwargs['smtp_additional_addresses'] = \"\"\n expected_kwargs['smtp_error_addresses'] = \"\"\n expected_kwargs['smtp_to_submitter'] = False\n expected_kwargs['smtp_to_pkgowner'] = False\n reactor_dict['artifacts_allowed_domains'] = ('domain1', 'domain2')\n expected_kwargs['artifacts_allowed_domains'] =\\\n ','.join(reactor_dict['artifacts_allowed_domains'])\n reactor_dict['yum_proxy'] = 'yum proxy'\n expected_kwargs['yum_proxy'] = reactor_dict['yum_proxy']\n reactor_dict['content_versions'] = ['v2']\n expected_kwargs['registry_api_versions'] = 'v2'\n\n # Move client config from plugin args to reactor config\n reactor_dict['clusters_client_config_dir'] = plugin_args.pop('osbs_client_config')\n\n if config_kwargs and 'equal_labels' in config_kwargs:\n expected_kwargs['equal_labels'] = config_kwargs['equal_labels']\n\n label_groups = [x.strip() for x in config_kwargs['equal_labels'].split(',')]\n\n equal_labels = []\n for label_group in label_groups:\n equal_labels.append([label.strip() for label in label_group.split(':')])\n\n reactor_dict['image_equal_labels'] = equal_labels\n\n reactor_dict['clusters'] = clusters\n reactor_dict['platform_descriptors'] = [{'platform': 'x86_64',\n 'architecture': 'amd64'}]\n\n workflow.plugin_workspace[ReactorConfigPlugin.key] = {}\n workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\\\n ReactorConfig(reactor_dict)\n\n add_koji_map_in_workflow(workflow, hub_url='/', root_url='')\n\n with open(os.path.join(str(tmpdir), 'osbs.conf'), 'w') as f:\n for plat_clusters in clusters.values():\n for cluster in plat_clusters:\n f.write(dedent(\"\"\"\\\n [{name}]\n openshift_url = https://{name}.com/\n namespace = {name}_namespace\n \"\"\".format(name=cluster['name'])))\n\n goarch = {'x86_64': 'amd64'}\n plugin_args['goarch'] = goarch\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args\n }]\n )\n\n # Update with config_kwargs last to ensure that, when set\n # always has precedence over worker_build_image param.\n if config_kwargs is not None:\n expected_kwargs.update(config_kwargs)\n expected_kwargs['build_from'] = 'image:registry/some_image@sha256:123456'\n\n (flexmock(atomic_reactor.plugins.pre_reactor_config)\n .should_receive('get_openshift_session')\n .and_return(None))\n\n (flexmock(Configuration).should_call('__init__').with_args(**expected_kwargs).once())\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n assert (build_result.annotations == {\n 'worker-builds': {\n 'x86_64': {\n 'build': {\n 'build-name': 'worker-build-x86_64',\n 'cluster-url': 'https://worker_x86_64.com/',\n 'namespace': 'worker_x86_64_namespace'\n },\n 'digests': [],\n 'plugins-metadata': {}\n }\n }\n })\n\n build_info = get_worker_build_info(workflow, 'x86_64')\n assert build_info.osbs\n\n for record in caplog.records:\n if not record.name.startswith(\"atomic_reactor\"):\n continue\n\n assert hasattr(record, 'arch')\n if record.funcName == 'watch_logs':\n assert record.arch == 'x86_64'\n else:\n assert record.arch == '-'\n\n\n@pytest.mark.parametrize('metadata_fragment', [\n True,\n False\n])\ndef test_orchestrate_build_annotations_and_labels(tmpdir, metadata_fragment):\n workflow = mock_workflow(tmpdir)\n mock_osbs()\n mock_manifest_list()\n\n md = {\n 'metadata_fragment': 'configmap/spam-md',\n 'metadata_fragment_key': 'metadata.json'\n }\n\n def mock_wait_for_build_to_finish(build_name):\n annotations = {\n 'digests': json.dumps([\n {\n 'digest': 'sha256:{}-digest'.format(build_name),\n 'tag': '{}-latest'.format(build_name),\n 'registry': '{}-registry'.format(build_name),\n 'repository': '{}-repository'.format(build_name),\n },\n ]),\n }\n if metadata_fragment:\n annotations.update(md)\n return make_build_response(build_name, 'Complete', annotations)\n\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'max_cluster_fails': 2,\n 'unreachable_cluster_retry_delay': .1,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n build_result = runner.run()\n assert not build_result.is_failed()\n\n expected = {\n 'worker-builds': {\n 'x86_64': {\n 'build': {\n 'build-name': 'worker-build-x86_64',\n 'cluster-url': 'https://worker_x86_64.com/',\n 'namespace': 'worker_x86_64_namespace'\n },\n 'digests': [\n {\n 'digest': 'sha256:worker-build-x86_64-digest',\n 'tag': 'worker-build-x86_64-latest',\n 'registry': 'worker-build-x86_64-registry',\n 'repository': 'worker-build-x86_64-repository',\n },\n ],\n 'plugins-metadata': {}\n },\n 'ppc64le': {\n 'build': {\n 'build-name': 'worker-build-ppc64le',\n 'cluster-url': 'https://worker_ppc64le.com/',\n 'namespace': 'worker_ppc64le_namespace'\n },\n 'digests': [\n {\n 'digest': 'sha256:worker-build-ppc64le-digest',\n 'tag': 'worker-build-ppc64le-latest',\n 'registry': 'worker-build-ppc64le-registry',\n 'repository': 'worker-build-ppc64le-repository',\n },\n ],\n 'plugins-metadata': {}\n },\n },\n }\n if metadata_fragment:\n expected['worker-builds']['x86_64'].update(md)\n expected['worker-builds']['ppc64le'].update(md)\n\n assert (build_result.annotations == expected)\n\n build_info = get_worker_build_info(workflow, 'x86_64')\n assert build_info.osbs\n\n koji_upload_dir = get_koji_upload_dir(workflow)\n assert koji_upload_dir\n\n\ndef test_orchestrate_choose_cluster_retry(tmpdir):\n\n mock_osbs()\n mock_manifest_list()\n\n (flexmock(OSBS).should_receive('list_builds')\n .and_raise(OsbsException)\n .and_raise(OsbsException)\n .and_return([1, 2, 3]))\n\n workflow = mock_workflow(tmpdir)\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_x86_64', 5), ('spam', 4)]\n ],\n 'ppc64le': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_ppc64le', 5), ('ham', 5)]\n ]\n })\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'max_cluster_fails': 2,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n runner.run()\n\n\ndef test_orchestrate_choose_cluster_retry_timeout(tmpdir):\n\n mock_manifest_list()\n (flexmock(OSBS).should_receive('list_builds')\n .and_raise(OsbsException)\n .and_raise(OsbsException)\n .and_raise(OsbsException))\n\n workflow = mock_workflow(tmpdir)\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_x86_64', 5), ('spam', 4)]\n ],\n 'ppc64le': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in [('chosen_ppc64le', 5), ('ham', 5)]\n ]\n })\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'max_cluster_fails': 2,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert build_result.is_failed()\n fail_reason = json.loads(build_result.fail_reason)['ppc64le']['general']\n assert 'Could not find appropriate cluster for worker build.' in fail_reason\n\n\ndef test_orchestrate_build_cancelation(tmpdir):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs()\n mock_manifest_list()\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n def mock_wait_for_build_to_finish(build_name):\n return make_build_response(build_name, 'Running')\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n\n flexmock(OSBS).should_receive('cancel_build').once()\n\n (flexmock(AsyncResult).should_receive('ready')\n .and_return(False) # normal execution\n .and_return(False) # after cancel_build\n .and_return(True)) # finally succeed\n\n class RaiseOnce(object):\n \"\"\"\n Only raise an exception the first time this mocked wait() method\n is called.\n \"\"\"\n\n def __init__(self):\n self.exception_raised = False\n\n def get(self, timeout=None):\n time.sleep(0.1)\n if not self.exception_raised:\n self.exception_raised = True\n raise BuildCanceledException()\n\n raise_once = RaiseOnce()\n (flexmock(AsyncResult).should_receive('get')\n .replace_with(raise_once.get))\n\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n assert 'BuildCanceledException' in str(exc.value)\n\n\n@pytest.mark.parametrize(('clusters_x86_64'), (\n ([('chosen_x86_64', 5), ('spam', 4)]),\n ([('chosen_x86_64', 5000), ('spam', 4)]),\n ([('spam', 4), ('chosen_x86_64', 5)]),\n ([('chosen_x86_64', 5), ('spam', 4), ('bacon', 4)]),\n ([('chosen_x86_64', 5), ('spam', 5)]),\n ([('chosen_x86_64', 1), ('spam', 1)]),\n ([('chosen_x86_64', 2), ('spam', 2)]),\n))\n@pytest.mark.parametrize(('clusters_ppc64le'), (\n ([('chosen_ppc64le', 7), ('eggs', 6)]),\n))\ndef test_orchestrate_build_choose_clusters(tmpdir, clusters_x86_64, clusters_ppc64le):\n workflow = mock_workflow(tmpdir)\n mock_osbs() # Current builds is a constant 2\n mock_manifest_list()\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in clusters_x86_64\n ],\n 'ppc64le': [\n {'name': cluster[0], 'max_concurrent_builds': cluster[1]}\n for cluster in clusters_ppc64le\n ]\n })\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n annotations = build_result.annotations\n assert set(annotations['worker-builds'].keys()) == {'x86_64', 'ppc64le'}\n for plat, plat_annotations in annotations['worker-builds'].items():\n assert plat_annotations['build']['cluster-url'] == 'https://chosen_{}.com/'.format(plat)\n\n\n# This test tests code paths that can no longer be hit in actual operation since\n# we exclude platforms with no clusters in check_and_set_platforms.\ndef test_orchestrate_build_unknown_platform(tmpdir): # noqa\n workflow = mock_workflow(tmpdir, platforms=['x86_64', 'spam'])\n mock_osbs()\n mock_manifest_list()\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n # Explicitly leaving off 'eggs' platform to\n # ensure no errors occur when unknow platform\n # is provided in exclude-platform file.\n 'platforms': ['x86_64', 'spam'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n\n assert \"No clusters found for platform spam!\" in str(exc.value)\n\n\ndef test_orchestrate_build_failed_create(tmpdir):\n workflow = mock_workflow(tmpdir)\n mock_osbs()\n mock_manifest_list()\n\n def mock_create_worker_build(**kwargs):\n if kwargs['platform'] == 'ppc64le':\n raise OsbsException('it happens')\n return make_build_response('worker-build-1', 'Running')\n (flexmock(OSBS)\n .should_receive('create_worker_build')\n .replace_with(mock_create_worker_build))\n\n fail_reason = 'build not started'\n annotation_keys = {'x86_64'}\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'failure_retry_delay': .1,\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert build_result.is_failed()\n\n annotations = build_result.annotations\n assert set(annotations['worker-builds'].keys()) == annotation_keys\n fail_reason = json.loads(build_result.fail_reason)['ppc64le']['general']\n assert \"Could not find appropriate cluster for worker build.\" in fail_reason\n\n\n@pytest.mark.parametrize('pod_available,pod_failure_reason,expected,cancel_fails', [\n # get_pod_for_build() returns error\n (False,\n None,\n KeyError,\n False),\n\n # get_failure_reason() not available in PodResponse\n (True,\n AttributeError(\"'module' object has no attribute 'get_failure_reason'\"),\n KeyError,\n False),\n\n # get_failure_reason() result used\n (True,\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n False),\n\n # cancel_build() fails (and failure is ignored)\n (True,\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n {\n 'reason': 'reason message',\n 'exitCode': 23,\n 'containerID': 'abc123',\n },\n True)\n])\ndef test_orchestrate_build_failed_waiting(tmpdir,\n pod_available,\n pod_failure_reason,\n cancel_fails,\n expected):\n workflow = mock_workflow(tmpdir)\n mock_osbs()\n\n class MockPodResponse(object):\n def __init__(self, pod_failure_reason):\n self.pod_failure_reason = pod_failure_reason\n\n def get_failure_reason(self):\n if isinstance(self.pod_failure_reason, Exception):\n raise self.pod_failure_reason\n\n return self.pod_failure_reason\n\n def mock_wait_for_build_to_finish(build_name):\n if build_name == 'worker-build-ppc64le':\n raise OsbsException('it happens')\n return make_build_response(build_name, 'Failed')\n (flexmock(OSBS)\n .should_receive('wait_for_build_to_finish')\n .replace_with(mock_wait_for_build_to_finish))\n mock_manifest_list()\n\n cancel_build_expectation = flexmock(OSBS).should_receive('cancel_build')\n if cancel_fails:\n cancel_build_expectation.and_raise(OsbsException)\n\n cancel_build_expectation.once()\n\n expectation = flexmock(OSBS).should_receive('get_pod_for_build')\n if pod_available:\n expectation.and_return(MockPodResponse(pod_failure_reason))\n else:\n expectation.and_raise(OsbsException())\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n\n build_result = runner.run()\n assert build_result.is_failed()\n\n annotations = build_result.annotations\n assert set(annotations['worker-builds'].keys()) == {'x86_64', 'ppc64le'}\n fail_reason = json.loads(build_result.fail_reason)['ppc64le']\n\n if expected is KeyError:\n assert 'pod' not in fail_reason\n else:\n assert fail_reason['pod'] == expected\n\n\n@pytest.mark.parametrize(('task_id', 'error'), [\n ('1234567', None),\n ('bacon', 'ValueError'),\n (None, 'TypeError'),\n])\ndef test_orchestrate_build_get_fs_task_id(tmpdir, task_id, error):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs()\n\n mock_reactor_config(tmpdir)\n\n workflow.prebuild_results[PLUGIN_ADD_FILESYSTEM_KEY] = {\n 'filesystem-koji-task-id': task_id,\n }\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n }\n }]\n )\n\n if error is not None:\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n workflow.build_result.is_failed()\n assert error in str(exc.value)\n\n else:\n build_result = runner.run()\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize('fail_at', ('all', 'first'))\ndef test_orchestrate_build_failed_to_list_builds(tmpdir, fail_at):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n mock_osbs() # Current builds is a constant 2\n\n mock_reactor_config(tmpdir, {\n 'x86_64': [\n {'name': 'spam', 'max_concurrent_builds': 5},\n {'name': 'eggs', 'max_concurrent_builds': 5}\n ],\n })\n\n flexmock_chain = flexmock(OSBS).should_receive('list_builds').and_raise(OsbsException(\"foo\"))\n\n if fail_at == 'all':\n flexmock_chain.and_raise(OsbsException(\"foo\"))\n\n if fail_at == 'first':\n flexmock_chain.and_return(['a', 'b'])\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n 'find_cluster_retry_delay': .1,\n 'max_cluster_fails': 2\n }\n }]\n )\n if fail_at == 'first':\n build_result = runner.run()\n assert not build_result.is_failed()\n\n annotations = build_result.annotations\n assert annotations['worker-builds']['x86_64']['build']['cluster-url'] == 'https://eggs.com/'\n else:\n build_result = runner.run()\n assert build_result.is_failed()\n if fail_at == 'all':\n assert 'Could not find appropriate cluster for worker build.' \\\n in build_result.fail_reason\n\n\n@pytest.mark.parametrize('is_auto', [\n True,\n False\n])\ndef test_orchestrate_build_worker_build_kwargs(tmpdir, caplog, is_auto):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': is_auto,\n 'platform': 'x86_64',\n 'release': '10',\n 'arrangement_version': 6,\n 'parent_images_digests': {},\n 'operator_manifests_extract_platform': 'x86_64',\n }\n\n reactor_config_override = mock_reactor_config(tmpdir)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n workflow.prebuild_results[CheckAndSetRebuildPlugin.key] = is_auto\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize('overrides', [\n {None: '4242'},\n {'x86_64': '4242'},\n {'x86_64': '4242', None: '1111'},\n])\ndef test_orchestrate_override_build_kwarg(tmpdir, overrides):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': False,\n 'platform': 'x86_64',\n 'release': '4242',\n 'arrangement_version': 6,\n 'parent_images_digests': {},\n 'operator_manifests_extract_platform': 'x86_64',\n }\n reactor_config_override = mock_reactor_config(tmpdir)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n for plat, value in overrides.items():\n override_build_kwarg(workflow, 'release', value, plat)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n build_result = runner.run()\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize('content_versions', [\n ['v1', 'v2'],\n ['v1'],\n ['v2'],\n])\ndef test_orchestrate_override_content_versions(tmpdir, caplog, content_versions):\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': False,\n 'platform': 'x86_64',\n 'release': '10',\n 'arrangement_version': 6,\n 'parent_images_digests': {},\n 'operator_manifests_extract_platform': 'x86_64',\n }\n add_config = {\n 'platform_descriptors': [{\n 'platform': 'x86_64',\n 'architecture': 'amd64',\n }],\n 'content_versions': content_versions\n }\n\n reactor_config_override = mock_reactor_config(tmpdir, add_config=add_config)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n\n will_fail = False\n if 'v2' not in content_versions:\n will_fail = True\n else:\n reactor_config_override['content_versions'] = ['v2']\n\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n build_result = runner.run()\n if will_fail:\n assert build_result.is_failed()\n assert 'failed to create worker build' in caplog.text\n assert 'content_versions is empty' in caplog.text\n else:\n assert not build_result.is_failed()\n\n\n@pytest.mark.parametrize(('build', 'exc_str', 'bc', 'bc_cont', 'ims', 'ims_cont',\n 'ml', 'ml_cont'), [\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name_wrong\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}}},\n \"Build object is malformed, failed to fetch buildroot image\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind_wrong\": \"DockerImage\"}}}}},\n \"Build object is malformed, failed to fetch buildroot image\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"wrong_kind\"}}}}},\n \"Build kind isn't 'DockerImage' but\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"wrong\"}}},\n \"Build config type isn't BuildConfig :\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\"annotations\": {}}},\n \"Build wasn't created from BuildConfig and neither has 'from'\" +\n \" annotation, which is needed for specified arch\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"wrong\"})}}},\n \"Build annotation has unknown 'kind'\",\n None, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image@sha256:123456\"})}}},\n \"Buildroot image isn't manifest list, which is needed for specified arch\",\n None, None, None, None, False, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"wrong build config\"}}},\n \"Build config not found :\",\n False, None, None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"BuildConfig object is malformed\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {}}}}, None, None,\n None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\", \"name\": \"build config\"}}},\n \"BuildConfig object has unknown 'kind'\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"wrong_kind\"}}}}},\n None, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"ImageStreamTag not found\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"ImageStreamTag\",\n \"name\": \"wrong_ims\"}}}}},\n False, None, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"ImageStreamTag is malformed\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"ImageStreamTag\",\n \"name\": \"ims\"}}}}},\n True, {\"image\": {}}, None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n \"Image in imageStreamTag 'ims' is missing Labels\",\n True, {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"ImageStreamTag\",\n \"name\": \"ims\"}}}}},\n True, {\"image\": {\"dockerImageReference\": \"some@sha256:12345\",\n \"dockerImageMetadata\": {\"Config\": {}}}},\n None, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"Buildroot image isn't manifest list, which is needed for specified arch\",\n None, None, None, None, False, None),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"Platform for orchestrator 'x86_64' isn't in manifest list\",\n None, None, None, None, True, {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"some_image\"}]}),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot@sha256:1949494494\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"Orchestrator is using image digest 'osbs-buildroot@sha256:1949494494' \" +\n \"which isn't in manifest list\",\n None, None, None, None, True, {\"manifests\": [{\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"some_image\"}]}),\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/image@osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"DockerImage\",\n \"name\": \"registry/image:tag\"})}}},\n \"build_image for platform 'ppc64le' not available\",\n None, None, None, None, True, {\"manifests\": [{\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"osbs-buildroot:latest\"}]}),\n])\ndef test_set_build_image_raises(tmpdir, build, exc_str, bc, bc_cont, ims, ims_cont, ml, ml_cont):\n build = json.dumps(build)\n workflow = mock_workflow(tmpdir)\n\n orchestrator_default_platform = 'x86_64'\n (flexmock(platform)\n .should_receive('processor')\n .and_return(orchestrator_default_platform))\n\n flexmock(os, environ={'BUILD': build})\n mock_osbs()\n mock_reactor_config(tmpdir)\n\n if bc is False:\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_raise(OsbsException))\n if bc is True:\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_return(bc_cont))\n if ims is False:\n (flexmock(Openshift)\n .should_receive('get_image_stream_tag')\n .and_raise(OsbsException))\n if ims is True:\n (flexmock(Openshift)\n .should_receive('get_image_stream_tag')\n .and_return(fake_imagestream_tag(ims_cont)))\n if ml is False:\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(None))\n if ml is True:\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(fake_manifest_list(ml_cont)))\n\n plugin_args = {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'osbs-buildroot:latest',\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n with pytest.raises(PluginFailedException) as ex:\n runner.run()\n assert \"raised an exception: RuntimeError\" in str(ex.value)\n assert exc_str in str(ex.value)\n\n\n@pytest.mark.parametrize(('build', 'bc', 'bc_cont', 'ims', 'ims_cont',\n 'ml', 'ml_cont', 'platforms'), [\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"osbs-buildroot:latest\",\n \"kind\": \"DockerImage\"}}}}},\n None, None, None, None, None, None, ['x86_64']),\n\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/osbs-buildroot@sha256:12345\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"ImageStreamTag\",\n \"name\": \"image_stream_tag\"})}}},\n None, None, True,\n {\"image\": {\"dockerImageReference\": \"registry/osbs-buildroot:ims\"}},\n True,\n {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"sha256:987654321\"},\n {\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"sha256:12345\"}]},\n ['ppc64le', 'x86_64']),\n\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/osbs-buildroot@sha256:12345\",\n \"kind\": \"DockerImage\"}}}},\n \"metadata\": {\n \"annotations\": {\n \"from\": json.dumps({\"kind\": \"ImageStreamTag\",\n \"name\": \"image_stream_tag\"})}}},\n None, None, True,\n {\"image\": {\"dockerImageReference\": \"registry/osbs-buildroot@sha256:12345\",\n \"dockerImageMetadata\": {\n \"Config\": {\n \"Labels\": {\"release\": \"1\", \"version\": \"1.0\"}}}}},\n True,\n {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"sha256:987654321\"},\n {\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"sha256:12345\"}]},\n ['ppc64le', 'x86_64']),\n\n\n ({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": \"registry/osbs-buildroot@sha256:12345\",\n \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\",\n \"name\": \"build config\"}}},\n True,\n {\"spec\": {\"strategy\": {\"customStrategy\": {\"from\": {\"kind\": \"DockerImage\",\n \"name\": \"registry/osbs-buildroot:bc\"}}}}},\n False, None, True,\n {\"manifests\": [{\"platform\": {\"architecture\": \"ppc64le\"},\n \"digest\": \"sha256:987654321\"},\n {\"platform\": {\"architecture\": \"amd64\"},\n \"digest\": \"sha256:12345\"}]},\n ['ppc64le', 'x86_64']),\n])\ndef test_set_build_image_works(tmpdir, build, bc, bc_cont, ims, ims_cont, ml, ml_cont,\n platforms):\n build = json.dumps(build)\n workflow = mock_workflow(tmpdir, platforms=platforms)\n\n orchestrator_default_platform = 'x86_64'\n (flexmock(platform)\n .should_receive('processor')\n .and_return(orchestrator_default_platform))\n\n flexmock(os, environ={'BUILD': build})\n mock_osbs()\n mock_reactor_config(tmpdir)\n\n if bc is True:\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_return(bc_cont))\n if ims is True:\n (flexmock(Openshift)\n .should_receive('get_image_stream_tag')\n .and_return(fake_imagestream_tag(ims_cont)))\n if ml is True:\n (flexmock(atomic_reactor.util)\n .should_receive('get_manifest_list')\n .and_return(fake_manifest_list(ml_cont)))\n\n plugin_args = {\n 'platforms': platforms,\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'osbs-buildroot:latest',\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n runner.run()\n\n\n@pytest.mark.parametrize(('platforms', 'override'), [\n (['ppc64le', 'x86_64'], ['ppc64le']),\n (['ppc64le'], ['ppc64le']),\n])\ndef test_set_build_image_with_override(tmpdir, platforms, override):\n workflow = mock_workflow(tmpdir, platforms=platforms)\n\n default_build_image = 'registry/osbs-buildroot@sha256:12345'\n build = json.dumps({\"spec\": {\n \"strategy\": {\n \"customStrategy\": {\n \"from\": {\"name\": default_build_image, \"kind\": \"DockerImage\"}}}},\n \"status\": {\n \"config\": {\"kind\": \"BuildConfig\", \"name\": \"build config\"}}})\n flexmock(os, environ={'BUILD': build})\n\n mock_osbs()\n mock_manifest_list()\n mock_orchestrator_platfrom()\n\n build_config = {\"spec\": {\"strategy\": {\n \"customStrategy\": {\n \"from\": {\"kind\": \"DockerImage\",\n \"name\": \"registry/osbs-buildroot:bc\"}}}}}\n (flexmock(Openshift)\n .should_receive('get_build_config')\n .and_return(build_config))\n\n reactor_config = {\n 'version': 1,\n 'clusters': deepcopy(DEFAULT_CLUSTERS),\n 'platform_descriptors': [{'platform': 'x86_64', 'architecture': 'amd64'}],\n 'build_image_override': {plat: 'registry/osbs-buildroot-{}:latest'.format(plat)\n for plat in override},\n }\n\n workflow.plugin_workspace[ReactorConfigPlugin.key] = {}\n workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\\\n ReactorConfig(reactor_config)\n\n add_koji_map_in_workflow(workflow, hub_url='/', root_url='')\n\n plugin_args = {\n 'platforms': platforms,\n 'build_kwargs': make_worker_build_kwargs(),\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{'name': OrchestrateBuildPlugin.key, 'args': plugin_args}]\n )\n\n runner.run()\n\n for plat in platforms:\n used_image = get_worker_build_info(workflow, plat).osbs.build_conf.get_build_from()\n expected_image = 'image:' + reactor_config['build_image_override'].get(plat,\n default_build_image)\n assert used_image == expected_image\n\n\ndef test_no_platforms(tmpdir):\n workflow = mock_workflow(tmpdir, platforms=[])\n mock_osbs()\n mock_reactor_config(tmpdir)\n\n (flexmock(OrchestrateBuildPlugin)\n .should_receive('set_build_image')\n .never())\n\n plugin_args = {\n 'platforms': [],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'osbs-buildroot:latest',\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n with pytest.raises(PluginFailedException) as exc:\n runner.run()\n assert 'No enabled platform to build on' in str(exc.value)\n\n\n@pytest.mark.parametrize('version,warning,exception', (\n (5, None, PluginFailedException),\n (6, None, None),\n))\ndef test_orchestrate_build_validate_arrangements(tmpdir, caplog, version, warning, exception):\n workflow = mock_workflow(tmpdir)\n mock_osbs() # Current builds is a constant 2\n mock_manifest_list()\n\n mock_reactor_config(tmpdir)\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': {\n 'platforms': ['x86_64', 'ppc64le'],\n 'build_kwargs': make_worker_build_kwargs(arrangement_version=version),\n 'osbs_client_config': str(tmpdir),\n 'goarch': {'x86_64': 'amd64'},\n }\n }]\n )\n if exception:\n with pytest.raises(exception):\n runner.run()\n else:\n runner.run()\n\n if warning:\n assert warning in caplog.text\n\n\ndef test_parent_images_digests(tmpdir, caplog):\n \"\"\"Test if manifest digests and media types of parent images are propagated\n correctly to OSBS client\"\"\"\n media_type = 'application/vnd.docker.distribution.manifest.list.v2+json'\n PARENT_IMAGES_DIGESTS = {\n 'registry.fedoraproject.org/fedora:latest': {\n media_type: 'sha256:123456789abcdef',\n }\n }\n\n workflow = mock_workflow(tmpdir, platforms=['x86_64'])\n workflow.builder.parent_images_digests.update(PARENT_IMAGES_DIGESTS)\n expected_kwargs = {\n 'git_uri': SOURCE['uri'],\n 'git_ref': 'master',\n 'git_branch': 'master',\n 'user': 'bacon',\n 'is_auto': False,\n 'platform': 'x86_64',\n 'release': '10',\n 'arrangement_version': 6,\n 'parent_images_digests': PARENT_IMAGES_DIGESTS,\n 'operator_manifests_extract_platform': 'x86_64',\n }\n\n reactor_config_override = mock_reactor_config(tmpdir)\n reactor_config_override['openshift'] = {\n 'auth': {'enable': None},\n 'build_json_dir': None,\n 'insecure': False,\n 'url': 'https://worker_x86_64.com/'\n }\n expected_kwargs['reactor_config_override'] = reactor_config_override\n mock_osbs(worker_expect=expected_kwargs)\n\n plugin_args = {\n 'platforms': ['x86_64'],\n 'build_kwargs': make_worker_build_kwargs(),\n 'worker_build_image': 'fedora:latest',\n 'osbs_client_config': str(tmpdir),\n }\n\n runner = BuildStepPluginsRunner(\n workflow.builder.tasker,\n workflow,\n [{\n 'name': OrchestrateBuildPlugin.key,\n 'args': plugin_args,\n }]\n )\n\n build_result = runner.run()\n assert not build_result.is_failed()\n","sub_path":"tests/plugins/test_orchestrate_build.py","file_name":"test_orchestrate_build.py","file_ext":"py","file_size_in_byte":56656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"106145237","text":"import datetime\nimport json\nimport re\nfrom collections import defaultdict\n\nimport numpy\nimport pandas as pd\nfrom pandas import DataFrame\n\nfrom utils.constant import 会话发起方式, 会话结束方式\n\n\ndef is_df_empty(df, tables):\n return all(df[table].shape[0] == 0 for table in tables)\n\n\ndef default(o): # numpy.int64 无法json化,因此在json.dumps时,要将其转化为int\n if isinstance(o, numpy.integer):\n return int(o)\n\n\nclass BaseStatis(object):\n def __init__(self, df, statis_type=1):\n self.df = df\n self.statis = dict()\n self.statis_type = statis_type\n if \"question_tag\" in self.df:\n self.tags = self._get_tags\n else:\n self.tags = {}\n\n def _table(self, table):\n if table in self.df:\n return self.df[table]\n else:\n return DataFrame({\"id\": []})\n\n def _series_index(self, series, idx):\n \"\"\"\n 根据索引获取一个Series对象的值\n \"\"\"\n if series.size > 0:\n return series.iloc[idx]\n else:\n return {}\n\n def _get_today_date(self, now, start='start'):\n if start == 'start':\n if now:\n return datetime.datetime.combine(\n datetime.date.today(),\n datetime.time.min) - datetime.timedelta(\n days=1)\n else:\n statistic_now = datetime.datetime.now() - datetime.timedelta(hours=1)\n year = statistic_now.year\n month = statistic_now.month\n day = statistic_now.day\n hour = statistic_now.hour\n return datetime.datetime(year=year, day=day, month=month,\n hour=hour)\n\n elif start == 'end':\n if now:\n return datetime.datetime.combine(\n datetime.date.today(),\n datetime.time.max) - datetime.timedelta(\n days=1)\n else:\n statistic_hour = datetime.datetime.now()\n year = statistic_hour.year\n month = statistic_hour.month\n day = statistic_hour.day\n hour = statistic_hour.hour\n return datetime.datetime(year=year, day=day, month=month,\n hour=hour) - datetime.timedelta(\n seconds=1)\n\n def _count(self, ser):\n return int(ser.id.count())\n\n @property\n def _get_tags(self):\n return {\n _tag.id: _tag.name for _tag in self.df[\"question_tag\"].itertuples()\n }\n\n def _json_dumps(self, d):\n return json.dumps(d, ensure_ascii=False, default=default)\n\n def _session_id(self, _id):\n if _id:\n df = self.df[\"chat_session\"]\n serie = df.loc[df[\"user_id\"] == _id]\n else:\n serie = self.df[\"chat_session\"]\n return serie[\"id\"].values\n\n def _kf_response(self, log_table):\n \"\"\"\n 客服回应会话\n :param log_table: chat_log\n :return:\n \"\"\"\n log_table = log_table.loc[\n (log_table.source == \"9\")\n & (log_table.raw.str.contains('\"from\": \"kf\"'))\n & ~(log_table.raw.str.contains('\"msg_type\": \"event\"'))\n & (log_table.raw.str.contains('\"is_sys_send\": 0'))\n ]\n return log_table\n\n def _msg_table(self, log_table):\n \"\"\"\n chat_log消息量\n :param log_table: chat_log\n :return:\n \"\"\"\n msg_table = log_table.loc[\n (log_table.source == \"9\")\n & (\n (log_table.raw.str.contains('\"from\": \"kf\"'))\n | (log_table.raw.str.contains('\"from\": \"user\"'))\n )\n & (log_table.raw.str.contains('\"is_sys_send\": 0'))\n ]\n return msg_table\n\n def _会话量(self, table):\n \"\"\"\n 总的会话数\n :param table: chat_session\n :return:\n \"\"\"\n num = table.loc[table.status == 2].groupby(\"ori_session\").groups\n return len(num)\n\n def _接待量(self, table):\n \"\"\"\n 总的接待数量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.user_id.notnull()) & (table.status == 2)]\n return self._count(df)\n\n def _机器人接待量(self, table):\n \"\"\"\n 机器人会话数量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.user_id.isnull()) & (table.creator == 0)]\n return self._count(df)\n\n def _排队会话量(self, table):\n \"\"\"\n 访客进入排队\n :param table:chat_queue\n :return:\n \"\"\"\n return self._count(table)\n\n def _人工会话量(self, table):\n \"\"\"\n 客服参与的会话数量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.status == 2) & (table.creator.isin([1, 9, 10, 11, 12, 13, 14, 15]))]\n return self._count(df)\n\n def _机器人转人工(self, table):\n \"\"\"\n 机器人转人工\n :param table:\n :return:\n \"\"\"\n df = table.loc[(table.status == 2) & (table.user_id.notnull()) & (table.creator == 1)]\n return self._count(df)\n\n def _人工消息量(self, session_table, log_table):\n \"\"\"\n 客服被动消息量\n :param session_table:\n :param log_table:\n :return:\n \"\"\"\n active_ori_sessions = set(session_table.loc[\n (session_table.status == 2)\n & (session_table.user_id.notnull())\n & (session_table.creator.isin([2, 3]))].ori_session.values)\n\n no_active_sids = set(session_table.loc[\n (session_table.status == 2)\n & (session_table.user_id.notnull())\n & ~(session_table.ori_session.isin(active_ori_sessions))].sid.values)\n\n msg = log_table.loc[\n (log_table.source == \"9\")\n & ~(log_table.raw.str.contains('\"msg_type\": \"event\"'))\n & (\n (log_table.raw.str.contains('\"from\": \"user\"'))\n | (log_table.raw.str.contains('\"from\": \"kf\"'))\n )\n & (\n (log_table.raw.str.contains('\"is_sys_send\": 0'))\n\n )\n & ~(log_table.raw.str.contains('\"text\": \"转机器人\"'))\n & (log_table.sid.isin(no_active_sids))\n ]\n\n visitor_msg = msg.loc[(msg.raw.str.contains('\"from\": \"user\"'))]\n kf_msg = msg.loc[(msg.raw.str.contains('\"from\": \"kf\"'))]\n return {\n \"总消息量\": int(msg.id.count()),\n \"访客消息量\": int(visitor_msg.id.count()),\n \"客服消息量\": int(kf_msg.id.count())\n }\n\n def _满意统计(self, table):\n \"\"\"\n 满意统计\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[(table.user_id.notnull()) & (table.status == 2)]\n df = df.sort_values('created', ascending=False).groupby('ori_session',\n as_index=False).first()\n satisfaction = df[\"satisfaction\"]\n size = satisfaction.size\n satis = satisfaction.value_counts()\n 评价总量 = size\n 非常满意 = satis.get(5, 0)\n 满意 = satis.get(4, 0)\n 一般 = satis.get(3, 0)\n 不满意 = satis.get(2, 0)\n 非常不满意 = satis.get(1, 0)\n 未评价 = 评价总量 - (非常满意 + 满意 + 一般 + 不满意 + 非常不满意)\n if not size:\n return {\"未评价\": 0, \"非常不满意\": 0, \"不满意\": 0, \"一般\": 0, \"满意\": 0,\n \"非常满意\": 0, \"评价总量\": 0}\n return {\"未评价\": 未评价, \"非常不满意\": 非常不满意, \"不满意\": 不满意, \"一般\": 一般, \"满意\": 满意,\n \"非常满意\": 非常满意, \"评价总量\": 评价总量}\n\n def _一次性解决量(self, table):\n \"\"\"\n 一次性解决率\n :param table: chat_session\n :return:\n \"\"\"\n table = table.loc[\n (table.status == 2)\n & (table.one_solved_status == 1)\n & (table.creator.isin([1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]))]\n return self._count(table)\n\n def _解决方式(self, table):\n \"\"\"\n 访客解决数量\n :param table:\n :return:\n \"\"\"\n human_table = table.loc[(table.status == 2) & (table.question_status == 1) & (table.user_id.notnull())]\n human_deal = int(human_table.user_id.describe()[\"count\"])\n\n # 机器人解决量\n robot_df = table.loc[\n (table.status == 2)\n & (\n (\n (table.creator == 会话发起方式[\"机器人\"])\n & (table.stop_way == 会话结束方式[\"机器人超时结束\"])\n )\n | (\n (table.creator == 会话发起方式[\"客户入队列\"])\n & (table.stop_way.isin([会话结束方式[\"放弃排队\"], 会话结束方式[\"客服都下线出队\"]]))\n )\n )]\n\n return {\"human\": human_deal, \"robot\": self._count(robot_df)}\n\n def _用户咨询分类(self, table):\n \"\"\"\n :param table: chat_session\n :return: {\"tag1\": \"id\": tag1_id, \"count\": 0, \"sub_tags\": {\"id\": tag2_id, \"count\": 0}}\n \"\"\"\n # 用户分类咨询\n df = table.loc[table.user_id.notnull() & (table.status == 2)]\n df = df.sort_values('created', ascending=False).groupby('ori_session',\n as_index=False).first()\n df = df.fillna(value=0)\n total_num = df[\"tag1\"].size\n\n classify, num1, num2 = {\"未分类\": 0}, 0, 0\n for tag in df.itertuples():\n tag1_content = self.tags.get(int(tag.tag1))\n tag2_content = self.tags.get(int(tag.tag2))\n classify[\"分类总数\"] = total_num\n\n if tag1_content:\n if tag1_content not in classify:\n classify[tag1_content] = {\n \"id\": int(tag.tag1),\n \"count\": 1,\n \"sub_tags\": {}\n }\n\n else:\n classify[tag1_content][\"count\"] += 1\n\n if tag2_content not in classify.get(tag1_content).get(\n \"sub_tags\") and tag2_content:\n sdict = {\n tag2_content: {\"id\": int(tag.tag2), \"count\": 1}}\n classify[tag1_content][\"sub_tags\"].update(sdict)\n elif tag2_content in classify.get(tag1_content).get(\n \"sub_tags\") and tag2_content:\n classify[tag1_content][\"sub_tags\"][tag2_content][\n \"count\"] += 1\n else:\n classify[\"未分类\"] += 1\n return classify\n\n def _客服会话时长(self, chat_session, chat_log):\n \"\"\"\n 客服已接待时长(会话段)\n :param chat_session:\n :param chat_log:\n :return: 各会话的时间比\n \"\"\"\n log_sids = set(self._kf_response(chat_log).sid.values)\n reception_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & ~(chat_session.creator.isin([2, 3]))]\n session = {\n \"<2m\": 0,\n \"2m-4m\": 0,\n \"4m-6m\": 0,\n \"6m-8m\": 0,\n \">8m\": 0,\n \"all\": 0\n }\n for each_session in reception_session.itertuples():\n _time = (each_session.stop_time - each_session.created).total_seconds()\n if _time <= 120:\n session[\"<2m\"] += 1\n elif 120 < _time <= 240:\n session[\"2m-4m\"] += 1\n elif 240 < _time <= 360:\n session[\"4m-6m\"] += 1\n elif 360 < _time <= 480:\n session[\"6m-8m\"] += 1\n elif _time > 480:\n session[\">8m\"] += 1\n session[\"all\"] += _time\n return session\n\n def _会话时长(self, chat_session, chat_log):\n \"\"\"\n 客服会话时长(按会话量)\n :param chat_session:\n :param chat_log:\n :return:\n \"\"\"\n log_sids = set(self._kf_response(chat_log).sid.values)\n reception_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & ~(chat_session.creator.isin([2, 3]))]\n reception_session_ori_session = set(reception_session.ori_session.values)\n rest_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.ori_session.isin(reception_session_ori_session))]\n session = {\n \"<2m\": 0,\n \"2m-4m\": 0,\n \"4m-6m\": 0,\n \"6m-8m\": 0,\n \">8m\": 0,\n \"all\": 0,\n \"total_count\": 0\n }\n for ori_session, dataframe in rest_session.groupby(\"ori_session\"):\n if dataframe.shape[0] != 0:\n _time = (dataframe.iloc[-1].stop_time - dataframe.iloc[0].created).total_seconds()\n if _time <= 120:\n session[\"<2m\"] += 1\n elif 120 < _time <= 240:\n session[\"2m-4m\"] += 1\n elif 240 < _time <= 360:\n session[\"4m-6m\"] += 1\n elif 360 < _time <= 480:\n session[\"6m-8m\"] += 1\n elif _time > 480:\n session[\">8m\"] += 1\n session[\"all\"] += _time\n session[\"total_count\"] += 1\n return session\n\n def _客服响应时长(self, chat_session, chat_log):\n \"\"\"\n 客服响应时长\n :param chat_session:\n :param chat_log:\n :return: 客服 会话段的响应时长\n \"\"\"\n # kf_response\n log_kf_respose = self._kf_response(chat_log)\n sids_useful = set(log_kf_respose.sid.values)\n\n # 找到chat_session对应sid -> created\n sid_createds = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & ~(chat_session.sid.isin([2, 3]))\n & (chat_session.sid.isin(sids_useful))]\n\n sid_created_mapping = {each_session.sid: each_session.created for each_session in sid_createds.itertuples()}\n\n # 筛选满足要求chat_session 去除主动的sid\n not_satisfy_sid = set(chat_session.loc[chat_session.creator.isin([2, 3])].sid.values)\n rest_log = chat_log.loc[chat_log.sid.isin(sids_useful) & ~(chat_log.sid.isin(not_satisfy_sid))]\n\n # 区分每一个sid\n kf_response = {}\n first_response = {}\n for sid, dataframe in rest_log.sort_values('created', ascending=True).groupby('sid', as_index=False):\n sid_list, only_one_kf, user_status = [], [], False\n for each_log in dataframe.itertuples():\n content = each_log.raw\n _type = re.search(r'\"msg_type\": \"event\"', content)\n _from = re.findall(r'\"from\": \"(\\w+)\"', content)\n _sys = re.search(r'\"is_sys_send\": 0', content)\n if _type and _from and not user_status and not _sys:\n if _from[0] == \"kf\":\n if not sid_list:\n sid_list.append({\"from\": \"user\", \"time\": dataframe.iloc[0].created})\n user_status = True\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": dataframe.iloc[0].created})\n\n if not _type and _from and not user_status and _sys:\n if _from[0] == \"user\":\n sid_list.append({\"from\": \"user\", \"time\": each_log.created})\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": each_log.created})\n user_status = True\n if user_status and not _type and _from and _sys:\n if sid_list:\n if sid_list[-1][\"from\"] != _from[0]:\n sid_list.append({\"from\": \"kf\", \"time\": each_log.created})\n user_status = False\n if len(only_one_kf) == 1:\n only_one_kf.append({\"from\": \"kf\", \"time\": each_log.created})\n\n if sid_list:\n if sid_list[-1][\"from\"] != \"kf\":\n sid_list.pop(-1)\n if only_one_kf:\n if only_one_kf[-1][\"from\"] != \"kf\":\n only_one_kf.pop(-1)\n\n kf_response[sid] = sid_list\n first_response[sid] = only_one_kf\n\n response = self._cal_response_time(kf_response)\n first_response = self._cal_response_time(first_response)\n return {\n \"响应时长\": response,\n \"响应数\": response.get(\"total_count\", 0),\n \"首次响应时长\": first_response,\n \"首次响应数\": first_response.get(\"total_count\", 0),\n \"30s应答数\": response.get(\"<15s\", 0) + response.get(\"15s-30s\", 0)}\n\n @staticmethod\n def _cal_response_time(time_data):\n \"\"\"\n 处理响应时长\n :return:\n \"\"\"\n response = defaultdict(dict)\n for key, value in time_data.items():\n if len(value) >= 2 and value[-1][\"from\"] != \"kf\":\n value.pop(-1)\n user = value[::2]\n kf = value[1::2]\n response[key] = [\n (each_kf[\"time\"] - each_user[\"time\"]).total_seconds() for each_user, each_kf in zip(user, kf)\n ]\n elif len(value) >= 2 and value[-1][\"from\"] == \"kf\":\n user = value[::2]\n kf = value[1::2]\n response_time = [(each_kf[\"time\"] - each_user[\"time\"]).total_seconds() for each_user, each_kf in\n zip(user, kf)]\n response[key] = response_time\n else:\n response[key] = []\n response_time = {\n \"<15s\": 0,\n \"15s-30s\": 0,\n \"30s-45s\": 0,\n \"45s-1m\": 0,\n \">1m\": 0,\n \"all\": 0,\n \"total_count\": 0\n }\n for sid, each_sid_time in response.items():\n if each_sid_time:\n for value in each_sid_time:\n if value <= 15:\n response_time[\"<15s\"] += 1\n elif 15 < value <= 30:\n response_time[\"15s-30s\"] += 1\n elif 30 < value <= 45:\n response_time[\"30s-45s\"] += 1\n elif 45 < value <= 60:\n response_time[\"45s-1m\"] += 1\n elif value > 60:\n response_time[\">1m\"] += 1\n response_time[\"total_count\"] += 1\n response_time[\"all\"] += value\n\n return response_time\n\n def _响应时长(self, chat_session, chat_log):\n \"\"\"\n 响应时长\n :param table:\n :return:\n \"\"\"\n # 获取有客服接待的会话 根据客服必须接待\n log_table = self._kf_response(chat_log)\n log_sids = set(log_table.sid.values)\n\n reception_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & ~(chat_session.creator.isin([2, 3]))]\n\n # 得到有客服响应的会话段 再得到整个会��\n ori_session = set(reception_session.ori_session.values)\n true_session = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.ori_session.isin(ori_session))\n & ~(chat_session.creator.isin([2, 3]))]\n true_sids = set(true_session.sid.values)\n\n # sid -> ori_session\n sids_ori_session = {\n tuple(set(dataframe.sid.values)): ori_session for ori_session, dataframe in\n true_session.groupby(\"ori_session\")}\n\n # chat_log 消息段包括访客的消息以及客服的消息\n rest_log = chat_log.loc[chat_log.sid.isin(true_sids)]\n\n # 获取sid dataframe 映射\n sid_dataframe = {sid: dataframe for sid, dataframe in rest_log.sort_values(\n by=[\"created\"], inplace=False, ascending=True).groupby(\"sid\")}\n\n ori_session_dataframes = {}\n for sids, ori_session in sids_ori_session.items():\n for sid in sids:\n if ori_session not in ori_session_dataframes:\n ori_session_dataframes[ori_session] = sid_dataframe.get(sid)\n else:\n ori_session_dataframes[ori_session] = pd.concat(\n [ori_session_dataframes[ori_session], sid_dataframe.get(sid)], axis=0).sort_values(\n by=[\"created\"], inplace=False, ascending=True)\n\n response = {}\n first_response = {}\n for ori_session, dataframe in ori_session_dataframes.items():\n sid_list, only_one_kf = [], []\n user_status = False\n for each_log in dataframe.itertuples():\n content = each_log.raw\n _type = re.search(r'\"msg_type\": \"event\"', content)\n _from = re.findall(r'\"from\": \"(\\w+)\"', content)\n _sys = re.search(r'\"is_sys_send\": 0', content)\n if _type and not user_status and _from and not _sys:\n if _from[0] == \"kf\":\n sid_list.append({\"from\": \"user\", \"time\": each_log.created})\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": each_log.created})\n user_status = True\n if not _type and _from and not user_status and _sys:\n if _from[0] == \"user\":\n sid_list.append({\"from\": \"user\", \"time\": each_log.created})\n if not only_one_kf:\n only_one_kf.append({\"from\": \"user\", \"time\": each_log.created})\n user_status = True\n if user_status and not _type and _from and _sys:\n if sid_list:\n if sid_list[-1][\"from\"] != _from[0]:\n sid_list.append({\"from\": \"kf\", \"time\": each_log.created})\n user_status = False\n if len(only_one_kf) == 1:\n only_one_kf.append({\"from\": \"kf\", \"time\": each_log.created})\n\n if sid_list:\n if sid_list[-1][\"from\"] != \"kf\":\n sid_list.pop(-1)\n if only_one_kf:\n if only_one_kf[-1][\"from\"] != \"kf\":\n only_one_kf.pop(-1)\n\n response[ori_session] = sid_list\n first_response[ori_session] = only_one_kf\n\n response = self._cal_response_time(response)\n first_response = self._cal_response_time(first_response)\n return {\n \"响应时长\": response,\n \"响应数\": response.get(\"total_count\", 0),\n \"首次响应时长\": first_response,\n \"首次响应数\": first_response.get(\"total_count\", 0),\n \"30s应答数\": response.get(\"<15s\", 0) + response.get(\"15s-30s\", 0)}\n\n def _机器人转人工会话量(self, table):\n \"\"\"\n 机器人转人工会话量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[table.user_id.notnull() & (table[\"creator\"] == 1) & (table[\"status\"] == 2)]\n return self._count(df)\n\n def _访客统计_用户来源(self, table):\n \"\"\"\n 访客来源\n :param table: chat_session 与 chat_user\n :return:\n \"\"\"\n session_df = table.get(\"session\")\n 总访客, 用户来源 = [], {\"h5\": [], \"weixin\": []}\n session_df = session_df.loc[\n (session_df.last_session.isnull()) & (session_df.user_id.isnull()) & (session_df[\"status\"] == 2)]\n for uid, dataframe in session_df.groupby(\"uid\"):\n 总访客.append(uid)\n sess = self._series_index(dataframe, 0)\n 用户来源[sess.get(\"source\")].append(uid)\n\n 新访客 = []\n for row in table.get(\"user\").itertuples():\n 新访客.append(row.uid)\n return self._json_dumps({\"总访客\": 总访客, \"新访客\": 新访客}), self._json_dumps(用户来源)\n\n def _进入排队人数(self, table):\n \"\"\"\n 获取排过队的人数\n :param table: chat_queue\n :return: nums\n \"\"\"\n if table.shape[0] == 0:\n return 0\n else:\n table = table.loc[table.status == 2]\n return self._count(table)\n\n def _转人工数量(self, table):\n \"\"\"\n 获取转人工解决量\n :param table: chat_session\n :return: 转人工的次数\n \"\"\"\n if table.shape[0] == 0:\n return 0\n robot_df = table.loc[(table.status == 2) & (table.user_id.isnull())]\n nums = 0\n for each_robot_msg in robot_df.itertuples():\n is_to_kf_status = json.loads(each_robot_msg.ext_bi) if each_robot_msg.ext_bi else {}\n if is_to_kf_status and \"to_kf\" in is_to_kf_status:\n if is_to_kf_status.get(\"to_kf\") == 1:\n nums += 1\n return nums\n\n def _排队进人工会话量(self, table):\n \"\"\"\n 通过排队最终进入人工会话的量\n :param table: table: chat_session\n :return: nums\n \"\"\"\n if table.shape[0] == 0:\n return 0\n else:\n table = table.loc[\n (table.status == 2)\n & (table.creator == 8)\n & (table.stop_way.isin([14, 15, 17, 19, 20]))]\n return self._count(table)\n\n def _服务总时长(self, table, now, statis_type):\n \"\"\"\n 客服服务时长\n :param table: chat_session\n :return: times (s)\n \"\"\"\n start_time = now - datetime.timedelta(days=1) if statis_type == 1 else now - datetime.timedelta(hours=1)\n end_time = now\n table = table.loc[\n (\n (table.user_id.notnull())\n & (table.status == 2)\n ) & (table.creator.isin(\n [\n 会话发起方式[\"客户转人工\"],\n 会话发起方式[\"客服转交客服\"],\n 会话发起方式[\"客服转交客服组\"],\n 会话发起方式[\"客服超时转交\"],\n 会话发起方式[\"客服强制下线转交\"],\n 会话发起方式[\"队列自动接入人工\"],\n 会话发起方式[\"队列手动接入人工\"],\n 会话发起方式[\"队列指派接入人工\"],\n 会话发起方式[\"关闭队列自动接入人工\"],\n 会话发起方式[\"队列指派到客服组\"],\n 会话发起方式[\"机器人转交客服\"],\n 会话发起方式[\"机器人转交客服组\"],\n 会话发起方式[\"强制转交给客服\"],\n 会话发起方式[\"强制转交给客服组\"],\n 会话发起方式[\"客服被动下线转交\"]\n ]))\n ]\n user_data = defaultdict(list)\n for user_id, data in table.groupby(\"user_id\"):\n for each in data.itertuples():\n created = pd.to_datetime(each.created)\n stop_time = pd.to_datetime(each.stop_time)\n user_data[int(user_id)].append([created, stop_time])\n haved_session_user = {}\n for user, user_content in user_data.items():\n haved_session_user[user] = self.cloc_service_time(user_content)\n return haved_session_user\n\n def _总独立接待量(self, chat_session, chat_log):\n \"\"\"\n 客服数据总览-独立接待量\n :param table: chat_session_ext\n :return:\n \"\"\"\n ori_session_ids = []\n chat_session = chat_session.loc[chat_session.user_id.notnull()]\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 9, 10, 11, 12, 13, 14, 15] and dataframe.shape[0] == 1:\n if dataframe.iloc[0].stop_way not in [9, 10, 23, 24, 25, 26, 28]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _总接待会话量(self, chat_session, chat_log):\n \"\"\"\n 客服数据总览-接待会话量\n :param chat_session: chat_session\n :param chat_log: chat_log\n :return:\n \"\"\"\n ori_session_ids = []\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 9, 10, 11, 12, 13, 14, 15]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _接入会话量(self, table):\n \"\"\"\n 客服工作量-接入会话量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ])\n )]\n return self._count(df)\n\n def _接待会话量(self, chat_session, chat_log):\n \"\"\"\n 客服工作量-接待会话量\n :param table: chat_session, chat_log\n :return:\n \"\"\"\n ori_session_ids = []\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _独立接待量(self, chat_session, chat_log):\n \"\"\"\n 客服工作量-独立接待量\n :param table: chat_session chat_log\n :return:\n \"\"\"\n ori_session_ids = []\n chat_session = chat_session.loc[chat_session.creator != 8]\n for ori_session, dataframe in chat_session.groupby(\"ori_session\"):\n if dataframe.iloc[0].creator in [1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] and \\\n dataframe.shape[0] == 1:\n if dataframe.iloc[0].stop_way not in [9, 10, 23, 24, 25, 26, 28]:\n ori_session_ids.append(ori_session)\n rest_session = chat_session.loc[chat_session.ori_session.isin(ori_session_ids)]\n\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n session_table = rest_session.loc[rest_session.sid.isin(log_sids)]\n\n count = 0\n for ori_session, dataframe in session_table.groupby(\"ori_session\"):\n count += 1\n return count\n\n def _首次未响应会话量(self, table):\n \"\"\"\n 客服工作量-首次未响应会话量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.stop_way.isin(\n [\n 会话结束方式[\"客服超时结束\"],\n 会话结束方式[\"客服超时转交\"]\n ]\n ))\n ]\n return self._count(df)\n\n def _结束会话量(self, chat_session, chat_log):\n \"\"\"\n 客服工作量-结束会话量\n :param table: chat_session\n :return:\n \"\"\"\n log_table = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & (~chat_log.raw.str.contains('\"msg_type\": \"event\"'))\n ]\n log_sids = set(log_table.sid.values)\n df = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.sid.isin(log_sids))\n & (chat_session.creator.isin([\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17,\n 会话发起方式[\"客服被动下线转交\"], # 18\n ]))\n & (chat_session.stop_way.isin(\n [\n 会话结束方式[\"客服超时结束\"],\n 会话结束方式[\"客服下线\"],\n 会话结束方式[\"用户手动\"],\n 会话结束方式[\"客服手动\"],\n 会话结束方式[\"用户超时结束\"],\n 会话结束方式[\"客服被动下线\"],\n 会话结束方式[\"客服强制下线结束\"],\n\n ]))\n ]\n return self._count(df)\n\n def _主动会话量(self, table):\n \"\"\"\n 客服工作量-主动会话量\n :param table:\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin(\n [\n 会话发起方式[\"客服激活\"],\n 会话发起方式[\"客服工单发起\"]\n ]\n ))]\n return self._count(df)\n\n def _主动转接量(self, table):\n \"\"\"\n 客服工作量-转接量\n :param table: chat_session\n :return:\n \"\"\"\n df = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin([\n\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17,\n 会话发起方式[\"客服被动下线转交\"], # 18\n ]))\n & (table.stop_way.isin([\n 会话结束方式[\"客服手动转交\"],\n 会话结束方式[\"客服转交客服组\"]\n ]))\n ]\n return self._count(df)\n\n def _接待总时长(self, table):\n \"\"\"\n 客服接待总时长\n :param table: chat_session\n :return:\n \"\"\"\n table = table.loc[\n (table.status == 2)\n & (table.user_id.notnull())\n & (table.creator.isin([1, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]))\n ]\n reception_time = 0\n for each_session in table.itertuples():\n reception_time += (each_session.stop_time - each_session.created).total_seconds()\n return reception_time\n\n def _未回复会话量_无效会话量(self, chat_session, chat_log):\n \"\"\"\n 未回复会话量\n :param chat_session:\n :param chat_log:\n :return:\n \"\"\"\n to_kf = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ])\n )]\n total_sids = set(to_kf.sid.values)\n\n visit = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"user\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & ~(chat_log.raw.str.contains('\"text\": \"转机器人\"'))\n & ~(chat_log.raw.str.contains('\"msg_type\": \"event\"'))]\n visit_sids = set(visit.sid.values) & total_sids\n\n kf = chat_log.loc[\n (chat_log.source == \"9\")\n & (chat_log.raw.str.contains('\"from\": \"kf\"'))\n & (chat_log.raw.str.contains('\"is_sys_send\": 0'))\n & ~(chat_log.raw.str.contains('\"msg_type\": \"event\"'))]\n kf_sids = set(kf.sid.values) & total_sids\n return len(total_sids - kf_sids), len(total_sids - visit_sids)\n\n def _问题解决_问题未解决(self, chat_session):\n \"\"\"\n 客服问题解决\n :param chat_session:\n :return:\n \"\"\"\n solve = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ]\n ))\n & (chat_session.question_status == 1)]\n no_solve = chat_session.loc[\n (chat_session.status == 2)\n & (chat_session.user_id.notnull())\n & (chat_session.creator.isin(\n [\n 会话发起方式[\"客户转人工\"], # 1\n 会话发起方式[\"客服转交客服\"], # 4\n 会话发起方式[\"客服转交客服组\"], # 5\n 会话发起方式[\"客服超时转交\"], # 6\n 会话发起方式[\"客服强制下线转交\"], # 7\n 会话发起方式[\"队列自动接入人工\"], # 9\n 会话发起方式[\"队列手动接入人工\"], # 10\n 会话发起方式[\"队列指派接入人工\"], # 11\n 会话发起方式[\"关闭队列自动接入人工\"], # 12\n 会话发起方式[\"队列指派到客服组\"], # 13\n 会话发起方式[\"机器人转交客服\"], # 14\n 会话发起方式[\"机器人转交客服组\"], # 15\n 会话发起方式[\"强制转交给客服\"], # 16\n 会话发起方式[\"强制转交给客服组\"], # 17\n 会话发起方式[\"客服被动下线转交\"] # 18\n ]\n ))\n & (chat_session.question_status == 0)]\n return self._count(solve), self._count(no_solve)\n\n\n @staticmethod\n def cloc_service_time(time_tuple_list):\n '''时间二元组列表, [(开始时间, 结束时间)]'''\n total_seconds = 0\n last_time = \"\"\n for start, end in time_tuple_list:\n if not last_time:\n total_seconds += (end - start).total_seconds()\n else:\n if last_time > start:\n total_seconds += (end - last_time).total_seconds()\n elif last_time <= start:\n total_seconds += (end - start).total_seconds()\n last_time = end\n return total_seconds if total_seconds >= 0 else 0\n\n\nif __name__ == \"__main__\":\n from utils.utils import get_db\n db = get_db()\n df = {}\n start = \"2018-12-05\"\n end = \"2018-12-25\"\n\n df[\"chat_session\"] = pd.read_sql_query(\n \"\"\"\n select c_s2.* from chat_session as c_s2 where c_s2.ori_session in \n (select c_s1.ori_session from chat_session as c_s1 \n where c_s1.created > \"{}\" \n and c_s1.created < \"{}\" and c_s1.sid = c_s1.ori_session)\n \"\"\".format(start, end), db.bind)\n df[\"chat_log\"] = pd.read_sql_query(\n \"\"\"\n select c_l.* from chat_log as c_l join \n (select * from chat_session as c_s2 where c_s2.ori_session in \n (select c_s1.ori_session from chat_session as c_s1 \n where c_s1.created > \"{}\" and c_s1.created < \"{}\" and c_s1.sid = c_s1.ori_session)) as c_s\n on c_l.sid = c_s.sid and c_l.uid = c_s.uid where c_l.created > \"{}\"\n \"\"\".format(start, end, start), db.bind\n )\n df[\"chat_user\"] = pd.read_sql_query(\n \"\"\"\n select * from chat_user where created > '{}' and created <= '{}'\n \"\"\".format(start, end), db.bind)\n df['question_tag'] = pd.read_sql_table('question_tag', db.bind)\n df['users'] = pd.read_sql_table(\"user\", db.bind)\n df[\"kf_status\"] = pd.read_sql_query(\n \"select * from company_setting where name = 'kf_status'\", db.bind)\n df[\"chat_queue\"] = pd.read_sql_query(\n \"select * from chat_queue where start_time > '{}' and start_time <= '{}'\".format(\n start, end), db.bind)\n\n for key, value in df.items():\n df[key] = value.loc[value.cid.isin([149, \"149\"])]\n\n # result = BaseStatis(df, statis_type=1)._会话时长(df[\"chat_session\"], df[\"chat_log\"])\n # result1 = BaseStatis(df, statis_type=1)._客服响应时长(df[\"chat_session\"], df[\"chat_log\"])\n # pprint(result1)\n # print()\n # result1 = BaseStatis(df, statis_type=1)._结束会话量(df[\"chat_session\"], df[\"chat_log\"])\n # result2 = BaseStatis(df, statis_type=1)._响应时长(df[\"chat_session\"], df[\"chat_log\"])\n # pprint(result2)\n\n base = BaseStatis(df, statis_type=1)\n\n db.close()\n","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":47942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"78953551","text":"# coding:utf-8\n\nfrom datetime import datetime\nimport json \n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required, permission_required \nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.db.models import Sum, Count\nfrom django.db import connection\nfrom django.core import serializers\nfrom templated_docs import fill_template\nfrom templated_docs.http import FileResponse\n\n\nfrom .models import Logistics, Bill, Product, Track, Warehouse, Tariff, Map, SendCar, OrderAir, Ticket, Imgs, OrderAir, SubTicket, Settle\nfrom logistics_set.models import Btype, Bill_option, Rate\nfrom customer.models import Customer\nfrom organization.models import Company\nfrom awb import Awb\nfrom extension import is_in_multiple_groups \n\n\ntoday = datetime.now()\nmonths = range(1, (int(today.month) + 1) )\n\n\ndef index(request):\n return render(request, 'logistics/index.html')\n\ndef detail(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n companys = Company.objects.all();\n return render(request, 'logistics/detail.html', {'pk': pk, 'hashid':hashid, 'logistics':logistics, 'companys':companys})\n except:\n return HttpResponseRedirect('/')\n \ndef broad(request):\n return render(request, 'logistics/broad.html')\n\ndef bill(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n # customer = Customer.objects.get(id=logistics.customer_id)\n sql = '''\n select (IFNULL(yingshou.rmb,0) - IFNULL(yingfu.rmb,0)) as res from\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应收') as yingshou,\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应付') as yingfu\n '''\n cursor=connection.cursor()\n cursor.execute(sql.format(pk=pk))\n profit = cursor.fetchone()[0]\n bill = Bill.objects.filter(logistics_id=pk)\n btype = Bill_option.objects.filter(btype=u'应收')\n ftype = Bill_option.objects.filter(btype=u'应付')\n rate = Rate.objects.all()\n blist = []\n flist = []\n for i in btype:\n blist.append(i.fee_name)\n for i in ftype:\n flist.append(i.fee_name)\n context = {'logistics': logistics,'bill': bill, 'pk': pk, 'hashid':hashid, 'rate':rate,\n 'blist':blist, 'flist':flist, 'profit':profit}\n return render(request, 'logistics/bill.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \ndef cost(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # customer = Customer.objects.get(id=logistics.customer_id)\n sql = '''\n select (IFNULL(yingshou.rmb,0) - IFNULL(yingfu.rmb,0)) as res from\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应收') as yingshou,\n (select sum(rmb) as rmb from logistics_bill where logistics_id = {pk} and bill_type='应付') as yingfu\n '''\n cursor=connection.cursor()\n cursor.execute(sql.format(pk=pk))\n profit = cursor.fetchone()[0]\n bill = Bill.objects.filter(logistics_id=pk)\n btype = Bill_option.objects.filter(btype=u'应收')\n ftype = Bill_option.objects.filter(btype=u'应付')\n rate = Rate.objects.all()\n blist = []\n flist = []\n for i in btype:\n blist.append(i.fee_name)\n for i in ftype:\n flist.append(i.fee_name)\n context = {'logistics': logistics,'bill': bill, 'pk': pk, 'hashid':hashid, 'rate':rate,\n 'blist':blist, 'flist':flist, 'profit':profit}\n return render(request, 'logistics/cost.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \n\ndef invoice(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n # customer = Customer.objects.get(id=logistics.customer_id)\n bill = Bill.objects.filter(logistics_id=pk).filter(bill_type=u'应付')\n btype = Bill_option.objects.filter(btype=u'应付')\n rate = Rate.objects.all()\n blist = []\n for i in btype:\n blist.append(i.fee_name)\n cursor = connection.cursor()\n cursor.execute('''select sum(rmb) as total from logistics_bill \n where bill_type='应付' and logistics_id=%s''' %pk)\n out_amount = cursor.fetchone()[0]\n cursor.close()\n context = {'logistics': logistics, 'bill': bill, 'pk': pk, 'hashid':hashid, 'rate':rate,\n 'blist':blist,'out_amount':out_amount}\n return render(request, 'logistics/invoice.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \ndef minvoice(request):\n return render(request, 'logistics/minvoice.html')\n\ndef track(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n tracks = Track.objects.filter(logistics_id=pk)\n # logistics = Logistics.objects.get(id=pk)\n context = {'pk': pk, 'hashid':hashid, 'tracks': tracks,'logistics':logistics}\n return render(request, 'logistics/track.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\n\ndef product(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n products = Product.objects.filter(logistics_id=pk)\n # logistics = Logistics.objects.get(id=pk)\n imgs = Imgs.objects.filter(logistics_id=pk)\n context = {'pk': pk, 'hashid':hashid, 'products': products,'logistics':logistics,'imgs':imgs}\n return render(request, 'logistics/product.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\n\ndef warehouse(request, pk, hashid):\n if not pk and hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n warehouses = Warehouse.objects.filter(logistics_id=pk)\n if len(warehouses) >= 1:\n warehouses = warehouses[0]\n context = {'pk': pk, 'hashid':hashid ,'warehouse': warehouses,'logistics':logistics}\n return render(request, 'logistics/warehouse.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\ndef safe(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n context = {'pk': pk, 'hashid':hashid, 'logistics':logistics}\n return render(request, 'logistics/safe.html', context=context)\n except:\n return HttpResponseRedirect('/')\n\ndef sendcar(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n maps = Map.objects.all()\n warehouses = Warehouse.objects.filter(logistics_id=pk)\n sendcar = SendCar.objects.filter(logistics_id=pk)\n context = {'pk': pk, 'hashid':hashid, 'sendcar': sendcar, 'logistics': logistics, 'maps':maps, 'warehouses': warehouses}\n return render(request, 'logistics/sendcar.html', context=context)\n except:\n return HttpResponseRedirect('/')\n \n\ndef maps(request):\n maps = Map.objects.all()\n return render(request, 'logistics/maps.html', {'maps': maps})\n\n\ndef mticket(request,pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n ticket = Ticket.objects.filter(logistics_id=pk)\n if len(ticket) > 0:\n ticket = ticket[0]\n return render(request, 'logistics/mticket.html', {'pk': pk, 'hashid':hashid,'logistics':logistics,'ticket':ticket})\n except:\n return HttpResponseRedirect('/')\n\ndef awb_print(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/awb_print.html', {'pk': pk, 'hashid':hashid ,'logistics':logistics})\n except:\n return HttpResponseRedirect('/')\n \n\ndef subtable(request,pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n sub_id = request.GET.get('sub_id')\n if sub_id:\n # logistics = Logistics.objects.get(id=pk)\n sub_ticket = SubTicket.objects.get(id=sub_id)\n return render(request, 'logistics/subtable.html', {'pk': pk, 'hashid':hashid ,'sub_id':sub_id,'logistics':logistics, 'sub_ticket':sub_ticket })\n else:\n return HttpResponse('错误请求,请联系管理员')\n except:\n return HttpResponseRedirect('/')\n\ndef subtable_list(request,pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n sublist = SubTicket.objects.filter(logistics_id=pk)\n return render(request, 'logistics/subticket_list.html', {'pk': pk,'hashid':hashid ,'logistics':logistics,'sublist':sublist})\n except:\n return HttpResponseRedirect('/')\n\n\ndef achiver(request,pk):\n logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/achiver.html', {'logistics': logistics, 'pk': pk, 'hashid':hashid})\n\n\ndef order_air(request,pk,hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n order_air = OrderAir.objects.filter(logistics_id=pk) \n return render(request, 'logistics/order_air.html', {'order_air': order_air, 'pk': pk, 'hashid':hashid, 'logistics': logistics})\n except:\n return HttpResponseRedirect('/')\n\n# \ndef order_air_list(request):\n return render(request, 'airline/cabin.html')\n \n\ndef order_air_list_detail(request,pk):\n orderair = OrderAir.objects.get(id=pk)\n return render(request, 'airline/cabin_detail.html',{'pk':pk,'orderair':orderair})\n\ndef order_air_list_track(request,pk):\n orderair = OrderAir.objects.get(id=pk)\n logistics = Logistics.objects.get(id=orderair.logistics_id)\n return render(request, 'airline/cabin_track.html',{'pk':pk,'orderair':orderair, 'logistics':logistics})\n \n\n@login_required\n@csrf_exempt\ndef order_air_change(request):\n if request.method == 'POST':\n pk = request.POST['pk']\n old = OrderAir.objects.filter(logistics_id=pk)\n for i in old:\n i.order_air_status = u'作废'\n # i.bill_no = null\n i.save()\n return HttpResponse('yes')\n else:\n return HttpResponse('bad request')\n\n\ndef settle(request,pk, hashid):\n '''\n 结算单\n '''\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk) \n bill = Bill.objects.filter(logistics_id=pk)\n instotal = bill.filter(bill_type='应收').aggregate(Sum('rmb')).get('rmb__sum', 0.00)\n outstotal = bill.filter(bill_type='应付').aggregate(Sum('rmb')).get('rmb__sum', 0.00)\n # settle = Settle.objects.get(logistics_id=pk)\n return render(request, 'logistics/settle.html', {'logistics': logistics, 'pk': pk,'hashid':hashid ,'instotal':instotal, 'outstotal':outstotal})\n except:\n return HttpResponseRedirect('/')\n\ndef manifest(request,pk, hashid): \n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n ticket = Ticket.objects.filter(logistics_id=pk)\n if len(ticket) > 0:\n ticket = ticket[0]\n sub_ticket = SubTicket.objects.filter(logistics_id=pk)\n return render(request, 'logistics/manifest.html', {'logistics': logistics, 'pk': pk,'hashid':hashid,'mawb':ticket,'hawb':sub_ticket})\n except:\n return HttpResponseRedirect('/') \n\n@login_required\ndef graph(request):\n return render(request, 'logistics/graph.html')\n\n\ndef onsite(request):\n return render(request, 'logistics/onsite.html')\n \n\ndef onsite_detail(request, pk):\n logistics = Logistics.objects.get(id=pk)\n imgs = Imgs.objects.filter(logistics_id=pk)\n return render(request, 'logistics/onsite_detail.html', {'pk':pk, 'logistics':logistics, 'imgs':imgs})\n \n@login_required\ndef exportAwb(request):\n pk = request.GET.get('pk')\n ticket = Ticket.objects.filter(logistics_id=pk).exists()\n if ticket:\n ticket = Ticket.objects.filter(logistics_id=pk).values()[0]\n logistics = Logistics.objects.filter(id=pk).values('other_fee','main_ticket_number')[0]\n if logistics['other_fee']:\n fees = json.loads(logistics['other_fee'])\n if fees:\n ticket['other_fee'] = fees\n ticket['main_ticket_number'] = logistics['main_ticket_number']\n return render(request, 'odt/awb.html', {'awb':ticket})\n # file = fill_template('odt/awb.ods', ticket, output_format='ods') \n # visible_filename = logistics['main_ticket_number']+'.ods'\n # return FileResponse(file, visible_filename) \n else:\n return HttpResponse(status=404)\n\ndef sign(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/sign.html', {'pk':pk,'hashid':hashid, 'logistics':logistics})\n except:\n return HttpResponseRedirect('/')\n\ndef entrust(request, pk, hashid):\n if not pk:\n return HttpResponseRedirect('/')\n else:\n if not hashid:\n return HttpResponseRedirect('/')\n else:\n try:\n logistics = Logistics.objects.get(id=pk, hashid=hashid)\n # logistics = Logistics.objects.get(id=pk)\n return render(request, 'logistics/entrust.html', {'pk':pk, 'hashid':hashid,'logistics':logistics})\n except:\n return HttpResponseRedirect('/')\n\ndef awb(request):\n return render(request, 'logistics/awb.html')","sub_path":"apps/logistics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"314792097","text":"#Sentiment Analysis of keyword \"Clinton\" from 2016-11-6 to 2016-10-12\r\n\r\nimport tweepy\r\nfrom textblob import TextBlob\r\n\r\nimport getoldtweets\r\nimport numpy as np\r\nimport operator\r\n\r\n\r\nconsumer_key= 'Consumer key from twitter'\r\nconsumer_secret= 'Consumer secret from twitter'\r\n\r\naccess_token='Access token from twitter'\r\naccess_token_secret='Access token secret from twitter'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\n\r\napi = tweepy.API(auth)\r\n\r\ntopic_name = \"Clinton\"\r\n#To find data for week 1\r\nsince_date = \"2016-11-6\"\r\nuntil_date = \"2016-11-12\"\r\n\r\ndef get_label(analysis, threshold = 0):\r\n\tif analysis.sentiment[0]>threshold:\r\n\t\treturn 'Positive'\r\n\telse:\r\n\t\treturn 'Negative'\r\n\r\nall_polarities = dict()\r\nfor topic_name in tweets:\r\n\tthis_topic_polarities = []\r\n\r\n\tthis_topic_tweets = api.search(q=[topic_name, topic], count=10000, since = since_date, until=until_date)\r\n\r\n\twith open('%s_tweets.csv' % topic, 'wb') as this_topic_file:\r\n\t\tthis_topic_file.write('tweet,sentiment_label\\n')\r\n\t\tfor tweet in this_topic_tweets:\r\n\t\t\tanalysis = TextBlob(tweet.text, pos_tagger=PatternTagger(), analyzer=PatternAnalyzer())\r\n\r\n\r\n\t\t\tthis_topic_polarities.append(analysis.sentiment[0])\r\n\t\t\tthis_topic_file.write('%s,%s\\n' % (tweet.text.encode('utf8'), get_label(analysis)))\r\n\r\n\r\n\tall_polarities[topic] = np.mean(this_topic_polarities)\r\n","sub_path":"sentiment_analysis/Clinton week 1.py","file_name":"Clinton week 1.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"601568993","text":"\"\"\"\nCloud file storage is a custom file storage object to store files on GCS\n\"\"\"\n\nimport uuid\nimport random\nimport string\nfrom datetime import datetime\nfrom django.conf import settings\nfrom django.core.files.storage import Storage\nfrom google_helpers import storage_service\nfrom googleapiclient import http\n\nclass CloudFileStorage(Storage):\n\n def __init__(self):\n self.storage = storage_service.get_storage_resource()\n\n def _open(self, name, mode):\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n return self.storage.objects().get(bucket=bucket, object=name).execute()\n\n #this can potentially cause a bad status line error\n def _save(self, name, content):\n media = http.MediaInMemoryUpload(content.read())\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n self.storage.objects().insert(\n bucket=bucket,\n name=name,\n media_body=media\n ).execute()\n return bucket + '/' + name\n\n def get_available_name(self, name):\n name = name.replace(\"./\", \"\")\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n time = datetime.now().strftime('%Y%m%d-%H%M%S%f')\n random_str = ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(8))\n name = time + '-' + random_str + '-' + name\n name = settings.MEDIA_FOLDER + name\n return bucket + '/' + name\n\n def size(self, name):\n filepath = name.split('/')\n bucket = filepath.pop(0)\n name = '/'.join(filepath)\n metadata = self.storage.objects().get(\n bucket=bucket,\n object=name\n ).execute()\n return metadata['size'];\n\n def deconstruct(self):\n return ('google_helpers.cloud_file_storage.CloudFileStorage', [], {})","sub_path":"google_helpers/cloud_file_storage.py","file_name":"cloud_file_storage.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"260827183","text":"# %% import packages\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# %% Model parameters\r\nN = 60500000\r\nkr = 1/7\r\nki0 = 0.25168\r\nke = 1 # α in original paper\r\nc1 = 63.7 # χ2 in original paper\r\nc2 = 0.135 # χ3 in original paper\r\nkca = 1/6 # ν in original paper\r\nn = 0.4 # f in original paper\r\nkc = kca * n # ν1 in original paper\r\nka = kca*(1-n) # ν2 in original paper\r\nTi = 10.5 # day at which the mitigation policy starts\r\n\r\n# %% simulation time settings\r\nTs = 1 # Time step [s]\r\nt_start = 0 \r\nt_stop = 300 \r\nN_sim =int((t_stop - t_start)/Ts) + 1 # Number of Time_steps\r\n\r\n# %% Preallocation of arrays for plotting :\r\nS = np.zeros(N_sim)\r\nV = np.zeros(N_sim)\r\nE = np.zeros(N_sim)\r\nX = np.zeros(N_sim)\r\nI = np.zeros(N_sim)\r\nC = np.zeros(N_sim)\r\nCC = np.zeros(N_sim)\r\nA = np.zeros(N_sim)\r\nR = np.zeros(N_sim)\r\nt= np.linspace(t_start,t_stop,N_sim)\r\n\r\n# %% Initialization :\r\nS[0] = N\r\nE[0] = (c1 + kca) / ke\r\nI[0]= (c1 * c2) / kc\r\nC[0] = 1\r\nCC[0] = 1\r\nA[0] = (ka*I[0])/(kr+c1)\r\nR[0] = 0\r\nX[0] = 1\r\nV[0] = 0\r\n\r\n# %% Simulation loop :\r\nfor k in range(0, N_sim-1):\r\n # Values of U\r\n if 0<= k <=27:\r\n U = 0.9 \r\n elif 28<= k <=33:\r\n U = 0.85\r\n elif 34<= k <=57:\r\n U = 0.2\r\n elif 58<= k <=67:\r\n U = 0.25\r\n elif 68<= k <=95:\r\n U = 0.5\r\n elif 96<= k <=140:\r\n U = 0.85\r\n else:\r\n U = 0.9\r\n # Mitigation Model \r\n dX_dt = (1/Ti)*(U-X[k])\r\n ki = ki0*X[k]\r\n \r\n # Values of Vaccination Efficiency\r\n if 50<= k <=N_sim-1:\r\n p = 0.5 \r\n else:\r\n p = 0\r\n \r\n # Vaccination Model \r\n dV_dt = p*S[k]\r\n \r\n # SEICAR Model\r\n dS_dt = -(ki/N)*(I[k]+A[k])*S[k] - p*S[k]\r\n dE_dt = ((ki/N)*(I[k]+A[k])*S[k]) - ke*E[k]\r\n dI_dt = ke*E[k]-kc*I[k]-ka*I[k]\r\n dC_dt = kc*I[k]-kr*C[k]\r\n dCC_dt = kc*I[k] # for cumulative confirmed cases just considering compartment C\r\n dA_dt = ka*I[k]-kr*A[k]\r\n dR_dt = kr*C[k]+kr*A[k] + p*S[k]\r\n \r\n # State updates using the Euler method :\r\n S[k+1] = S[k] + dS_dt *Ts\r\n E[k+1] = E[k] + dE_dt *Ts\r\n I[k+1] = I[k] + dI_dt *Ts\r\n C[k+1] = C[k] + dC_dt *Ts\r\n CC[k+1] = CC[k] + dCC_dt *Ts\r\n A[k+1] = A[k] + dA_dt *Ts\r\n R[k+1] = R[k] + dR_dt *Ts\r\n X[k+1] = X[k] + dX_dt *Ts\r\n V[k+1] = V[k] + dV_dt *Ts\r\n \r\n# %% Plotting :\r\nplt.close('all')\r\nplt.figure(1)\r\nplt.plot(t, CC)\r\nplt.legend(labels=('Cumulative Confirmed'))\r\nplt.grid()\r\nplt.show()\r\nprint(CC[249])","sub_path":"problem5_part2_with_mitigation.py","file_name":"problem5_part2_with_mitigation.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"564698238","text":"from django.core.mail import send_mail\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Count\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.generic import ListView\nfrom haystack.query import SearchQuerySet\nfrom .models import Comment, Post\nfrom .forms import CommentForm, EmailPostForm, SearchForm\nfrom taggit.models import Tag\n\n\n# Create your views here.\n\n\n# class PostListView(ListView):\n# queryset = Post.published.all() # This is equivalent to model = Post\n# context_object_name = 'posts'\n# paginate_by = 3\n# template_name = 'blog/post/list.html'\n\n\n# Function based view equivalent to PostListView\ndef post_list(request, tag_slug=None):\n object_list = Post.published.all()\n tag = None\n\n if tag_slug:\n tag = get_object_or_404(Tag, slug=tag_slug)\n object_list = object_list.filter(tags__in=[tag])\n\n posts_per_page = 3 # 3 posts in each page\n paginator = Paginator(object_list, posts_per_page)\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer deliver the first page\n posts = paginator.page(1)\n except EmptyPage:\n # If page is out of range deliver last page of rsults\n posts = paginator.page(paginator.num_pages)\n return render(request,\n 'blog/post/list.html',\n {'page': page,\n 'posts': posts,\n 'tag': tag})\n\n\ndef post_detail(request, year, month, day, post):\n post = get_object_or_404(Post, slug=post,\n status='published',\n publish__year = year,\n publish__month = month,\n publish__day = day)\n\n # List of active comments for this post\n # This is a QuerySet starting from the post object, and calling the related_name\n # attribute from the Comment model\n comments = post.comments.filter(active=True)\n\n if request.method == 'POST':\n # A comment was posted - instantiate the form using the submitted data\n comment_form = CommentForm(data=request.POST)\n\n if comment_form.is_valid():\n # Create Comment object but don't save to database yet\n # save() method creates an instance of the model that the form is\n # linked to\n new_comment = comment_form.save(commit=False)\n # Assign the current post to the comment just created\n new_comment.post = post\n # Save the comment to the database\n new_comment.save()\n else:\n comment_form = CommentForm()\n\n # List of similar posts to the one the user is viewing\n # Retrieve list of tags for the current psot\n post_tags_ids = post.tags.values_list('id', flat=True)\n # Get all similar posts based on tag id, but exclude the current post\n similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)\n # Use the Count aggregation function to generated a calculated field, same_tags\n # that contains number of tags shared with all the tags queried\n similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]\n return render(request,\n 'blog/post/detail.html',\n {'post': post,\n 'comments': comments,\n 'comment_form': comment_form,\n 'similar_posts': similar_posts})\n\ndef post_share(request, post_id):\n # Retrieve post id that will be shared\n post = get_object_or_404(Post, id=post_id, status='published')\n sent = False\n\n if request.method == 'POST':\n # Form was submitted - pull in the data that was submitted\n form = EmailPostForm(request.POST)\n if form.is_valid():\n # Form fields passed validation\n cd = form.cleaned_data\n post_url = request.build_absolute_uri(post.get_absolute_url())\n subject = '{} ({}) recommends you reading \"{}\"'.format(cd['name'], cd['email'], post.title)\n message = 'Read \"{}\" at {}\\n\\n{}\\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])\n send_mail(subject, message, 'admin@myblog.com', [cd['to']])\n sent=True\n else:\n form = EmailPostForm()\n return render(request, 'blog/post/share.html',\n {'post': post,\n 'form': form,\n 'sent': sent})\n\ndef post_search(request):\n # Instantiate the searchform\n form = SearchForm()\n if 'query' in request.GET:\n # When form is submitted, instantiate it\n # with the submitted GET data\n form = SearchForm(request.GET)\n if form.is_valid():\n cd = form.cleaned_data\n # Some issue with a model not being registered/communicated to\n # Haystack.\n r = SearchQuerySet().models(Post).filter(content=cd['query'])\n pk_list = [i.pk for i in r]\n results = Post.objects.filter(pk__in=pk_list)\n # count total results\n total_results = len(results)\n else:\n cd = {}\n results = {}\n total_results = {}\n return render(request,\n 'blog/post/search.html',\n {'form': form,\n 'cd' : cd,\n 'results': results,\n 'total_results': total_results})","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"375572746","text":"#coding=utf8\nimport csv\nimport json\nimport pymongo\nfrom pymongo import MongoClient\n\nimport os\n#处理type8\n\n# 遍历filepath下所有文件,包括子目录\ndef getAllFile(filepath):\n filenames = []\n files = os.listdir(filepath)\n for fi in files:\n fi_d = os.path.join(filepath,fi)\n if os.path.isdir(fi_d):\n getAllFile(fi_d)\n else:\n filenames.append(fi_d)\n # print(os.path.join(filepath,fi_d))\n return filenames\n# 把csv文件的数据以每行作为一个元素存储到到mdbuffer[]数组中\n\ndef readInToArray(filenames):\n # 存放csv中读取的数据\n mdbuffer = []\n flag = 0\n for filename in filenames:\n try:\n # 打开csv文件,设置读的权限\n csvHand = open(filename, \"r+\", encoding='utf-8', errors='ignore')\n # 创建读取csv文件句柄\n readcsv = csv.reader(csvHand)\n # 把csv的数据读取到mdbuffer中\n if flag == 0 :\n for row in readcsv:\n mdbuffer.append(row)\n # print(row)\n else:\n # print(next(readcsv))\n #跳过表中的第一行\n next(readcsv)\n for row in readcsv:\n mdbuffer.append(row)\n except Exception as e:\n print(\"Read Excel error:\", e)\n finally:\n # 关闭csv文件\n print(filename + \"finished\")\n csvHand.close()\n flag = 1\n return mdbuffer\n\ndef readIntoMongo(mdbuffer):\n # 建立MongoDB数据库连接\n # 远程数据库端\n client = MongoClient('36.26.80.184', 27017)\n # 连接所需数据库,test为数据库名\n db = client.bigdata_mongo\n # 连接所用集合,也就是我们通常所说的表,test为表名\n collection = db.indicators\n '''\n # 远程数据库端\n client = MongoClient('10.0.86.60', 27017)\n # 连接所需数据库,test为数据库名\n db = client.bigdata_mongo\n # 连接所用集合,也就是我们通常所说的表,test为表名\n collection = db.indicator\n\n '''\n '''\n #本地数据库测试\n client = MongoClient('localhost', 27017)\n # 连接所需数据库,test为数据库名\n db = client.bigdata_mongo\n # 连接所用集合,也就是我们通常所说的表,test为表名\n collection = db.test\n'''\n #对数据表进行处理\n\n #获取第一行\n head_row1 = mdbuffer[0]\n #获取第二行\n head_row = mdbuffer[1]\n #获得列数\n columnNumber = len(mdbuffer[0])\n # 获取mdbuffer中的元素个数,即数据表的行数\n rowNumber = len(mdbuffer)\n # 处理首行数据\n kind = head_row1[3]\n counrty_set = []\n time = []\n time_set = []\n\n\n #跳过第一行\n '''\n for row in range(1, rowNumber):\n temp = {}\n item = mdbuffer[row]\n counrty.append(item[0])\n time.append(item[5])\n counrty_set = set(counrty)\n time_set = set(time)\n '''\n for row in range(2, rowNumber):\n # propertyJson用来设置每个document的json数据属性格式\n propertyJson = {}\n #temp用来设置每个indicators属性\n temp = {}\n #获取得一行数据\n item = mdbuffer[row]\n propertyJson[\"Country\"] = item[0]\n propertyJson[\"Year\"] = item[2]\n propertyJson[\"Data_source\"] = 'WHO'\n for column in range(3,columnNumber):\n if column < len(item):\n if item[column].strip() == 'No data': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'Elimination verified': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'No PC required': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'Not applicable': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == '..': # 将缺省的数据填充为''空.\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == '':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column] == 'Not available':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column].strip() == '[ - ]':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column].strip() == '[ - 1]':\n temp[kind + head_row[column].replace('.', '_')] = ''\n elif item[column].strip() == '-':\n temp[kind + head_row[column].replace('.', '_')] = ''\n else: # 将字符串转化为float型数值\n if item[column].find('[') != -1:\n # print((item[column][:(item[column].find('[')-1)]).replace(' ',''))\n temp[kind + head_row[column].replace('.', '_')] = float(\n (item[column][:(item[column].find('[') - 1)]).replace(' ', ''))\n # elif item[column].strip().find('[') == 0:\n # temp[head_row[column]] = ''\n else:\n temp[kind + head_row[column].replace('.', '_')] = float((item[column]).replace(' ', ''))\n\n propertyJson[\"indicators\"] = temp\n print(propertyJson)\n #转换成josn的形式以便插入mongodb\n t = json.dumps(propertyJson)\n loaded_entry = json.loads(t)\n try:\n collection.insert_one(loaded_entry)\n except pymongo.errors.DuplicateKeyError as e:\n pass\n\n\nfiles = getAllFile('D:\\\\DataLab_Project\\\\data\\\\open_data\\\\whoi\\\\type8')\n\nfor item in files:\n path = []\n path.append(item)\n file = readInToArray(path)\n readIntoMongo(file)\nprint(len(file))","sub_path":"chentongbao/code/Indicator_Process/Indicator_process/whoi/whoi_process8.py","file_name":"whoi_process8.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"565542440","text":"import re\n\n\nclass Rle:\n \"\"\"\n Class for parse and modify\n Conway's game of life rle files.\n \"\"\"\n\n def __init__(self):\n self.__map__ = [[]]\n pass\n\n def string(self):\n \"\"\"\n Create rle string of this object\n (something like \"2ob$obo$bo!\").\n \"\"\"\n\n result = \"\"\n for i in range(len(self.__map__)):\n result += self.__make_native_string__(i)\n\n return Rle.__optimized_string__(result)\n\n def __make_native_string__(self, line):\n result = \"\"\n for cell in self.__map__[line]:\n if cell:\n result += 'o'\n else:\n result += 'b'\n\n return result\n\n @staticmethod\n def __optimized_string__(string):\n fake_element = [\"0x\"]\n elements = re.findall(\"\\d*[ob$]\", string) + fake_element\n previous = (Rle.__element_number__(elements[0]),\n Rle.__element_char__(elements[0]))\n\n result = \"\"\n\n for current in map(Rle.__parse_element__, elements[1::]):\n if current[1] == previous[1]:\n previous[0] += current[0]\n else:\n result += Rle.__make_element__(previous[0], previous[1])\n\n return result\n\n @staticmethod\n def __element_char__(element):\n return element[-1]\n\n @staticmethod\n def __element_number__(element):\n number = re.findall(\"\\d*\", element)[0]\n if number == \"\":\n return 1\n else:\n return int(number)\n\n @staticmethod\n def __parse_element__(element):\n return Rle.__element_number__(element), Rle.__element_char__(element)\n\n @staticmethod\n def __make_element__(number, char):\n if number == 1:\n return char\n else:\n return str(number) + char\n","sub_path":"RLE.py","file_name":"RLE.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"259912412","text":"# -*- coding: utf-8 -*-\nfrom flask import render_template, Flask, request, send_file\nfrom draw import edit_img, INPUT_FILE, FONT, FONT_SIZE\nimport StringIO\nimport logging\n\napp = Flask(__name__)\n\nhandler = logging.StreamHandler()\nhandler.setLevel(logging.INFO)\nhandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))\napp.logger.addHandler(handler)\napp.logger.handlers.extend(logging.getLogger(\"project-zombie.log\").handlers)\n\nlogger = app.logger\n\n@app.route('/', methods=['GET', 'POST'])\ndef generate_zombie():\n if request.method == 'GET':\n logger.error(\"Browser is {}\".format(request.user_agent.browser))\n logger.error(\"uas is {}\".format(request.user_agent.string))\n logger.error(\"platform is {}\".format(request.user_agent.platform))\n return render_template('index.html')\n elif request.method == 'POST':\n name = request.form.get('name').strip()\n logger.error(\"Sent love to {}\".format(name.encode('utf-8')))\n text_array = [name, \"粽有吉祥如意伴您左右\"]\n img = edit_img('tmp', \"tmp\", text_array[0].encode(\"utf-8\"), INPUT_FILE, FONT, FONT_SIZE, text_array, 1000, 10, True)\n img_io = StringIO.StringIO()\n img.save(img_io, 'JPEG', quality=100)\n img_io.seek(0)\n # adjustment for iOS\n as_attachment = False\n if request.user_agent.platform == \"iphone\":\n as_attachment = True\n return send_file(img_io, attachment_filename='wehome.jpg', as_attachment=as_attachment)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"155185419","text":"from itertools import product\n\ndef threeSplit(a):\n\n s = sum(a) // 3\n foo = [sum(a[:i+1]) for i in range(len(a))]\n bar = [i for i in range(len(a) - 2) if foo[i] == s]\n answer = [foo[i+1:-1].count(2 * s) for i in bar]\n return sum(answer)\n \n \"\"\" Time Limitation\n prod = product(range(len(a) - 1), repeat = 3)\n perms = [i for i in prod if sum(i) == len(a) and i.count(0) == 0]\n ans = [0 for f, s, t in perms if sum(a[:f]) == sum(a[f:f+s]) == sum(a[f+s:f+s+t])]\n return len(ans) \"\"\"\n","sub_path":"arcade/the_core/threeSplit.py","file_name":"threeSplit.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"164358189","text":"# userdb.py Control 역할\nimport sqlite3\n\nfrom sql import Sql\nfrom uservo import UserVO\n\n\nclass UserDB:\n def __init__(self, dbName):\n self.__dbName = dbName;\n def getConn(self):\n con = sqlite3.connect(self.__dbName);\n cursor = con.cursor();\n return {'con':con,'cursor':cursor};\n\n def close(self, cc):\n if cc['cursor'] != None:\n cc['cursor'].close();\n if cc['con'] != None:\n cc['con'].close();\n\n def makeTable(self):\n cc = self.getConn();\n cc['cursor'].execute(Sql.make_userdb);\n cc['con'].commit();\n self.close(cc);\n\n def insert(self, u):\n cc = self.getConn();\n cc['cursor'].execute(Sql.insert_userdb,\n (u.getId(),u.getPwd(),u.getName())\n );\n cc['con'].commit();\n self.close(cc);\n print('%s 등록 되었습니다.' % u);\n def delete(self,id):\n print('%s 삭제 되었습니다.' % id);\n def update(self, u):\n print('%s 수정 되었습니다.' % u);\n def select(self, id):\n result = None;\n cc = self.getConn();\n cc['cursor'].execute(Sql.select_userdb , (id,));\n obj = cc['cursor'].fetchone();\n result = UserVO(obj[0],obj[1],obj[2]);\n self.close(cc);\n return result;\n def selectall(self):\n results = [];\n cc = self.getConn();\n cc['cursor'].execute(Sql.selectall_userdb);\n all = cc['cursor'].fetchall();\n for u in all:\n rs = UserVO(u[0],u[1],u[2]);\n results.append(rs);\n self.close(cc);\n return results;\n\n\n\n\n\n","sub_path":"01_python/day088/userdb.py","file_name":"userdb.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"435542524","text":"from sys import stdin, setrecursionlimit\n\n\ndef main():\n input = stdin.buffer.readline\n s = list(input()[:-1].decode())\n n = len(s)\n l = r = -1\n ans = 0\n for i in range(1, n):\n if s[i] == s[i - 1]:\n if l == -1:\n l = i\n else:\n r = i\n if r != -1:\n ans += r - l\n r = l = -1\n if l != -1:\n ans += n - l\n print(min(ans, n - ans))\n\n\nif __name__ == \"__main__\":\n setrecursionlimit(10000)\n main()\n","sub_path":"Python_codes/p03073/s385005653.py","file_name":"s385005653.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"297712891","text":"\"\"\"\ndb wrapper for json-box\n\"\"\"\nimport sqlite3\nimport os\n\ntesting = False\n\nif os.getcwd().startswith(\"/var/www\"):\n DBNAME = \"/var/local/logger/logs.db\"\nelse:\n DBNAME = \"logs.db\"\n\nDBFLAGS = sqlite3.PARSE_COLNAMES | sqlite3.PARSE_DECLTYPES\n\n\ndef dict_factory(cursor, row):\n \"\"\"Return a dict for each row\"\"\"\n return {col[0]: row[idx] for idx, col in enumerate(cursor.description)}\n\n\n# a decorator to manage db access\ndef with_db(func):\n \"\"\"Add an extra argument with a database connection\"\"\"\n\n def func_wrapper(*args, **kwargs):\n db = sqlite3.connect(DBNAME, detect_types=DBFLAGS)\n db.row_factory = dict_factory\n result = func(*args, **dict(kwargs, db=db))\n db.commit()\n db.close()\n return result\n\n return func_wrapper\n\n\ndef insert(db, table, insertVerb=\"insert\", **fields):\n \"\"\"Insert an record into a table\"\"\"\n sql = \"%s into %s (%s) values (%s)\" % (\n insertVerb,\n table,\n \", \".join(fields.keys()),\n \", \".join([\"?\"] * len(fields)),\n )\n return db.execute(sql, tuple(fields.values()))\n\n\n@with_db\ndef createTables(db):\n db.execute(\n \"\"\"create table if not exists logs\n (id integer primary key,\n time timestamp,\n ip text,\n ref text,\n message json\n )\"\"\"\n )\n\n\ncreateTables()\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"618634547","text":"import csv\nimport os\nimport select\nimport sys\nimport termios\nimport time\nimport tty\nimport RPi.GPIO as GPIO\n\nimport pandas as pd\n\nfrom hx711py.hx711 import HX711 \n\n\ndef cleanAndExit():\n print(\"Cleaning...\")\n GPIO.cleanup()\n print(\"Bye!\")\n sys.exit()\n\ndef setup(hx, reference_unit):\n\n hx.set_reading_format(\"MSB\", \"MSB\")\n hx.set_reference_unit(reference_unit) \n hx.reset() \n hx.tare() \n print(\"Tare done! Add weight now...\")\n\ndef isData():\n return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])\n\n\n\nif __name__ == '__main__':\n subject = str(input(\"Who is the Subject?\\n\"))\n label = 'Not Sitting'\n old_settings = termios.tcgetattr(sys.stdin)\n data = None\n\n hx1 = HX711(14, 15) #8, 10\n #hx2 = HX711(21, 20) #38, 40\n hx3 = HX711(19, 26) #35, 37\n #hx4 = HX711(6, 13) #31, 33\n hx2 = HX711(6, 13)\n hx4 = HX711(21, 20)\n\n setup(hx1, -44)\n setup(hx2, -46)\n setup(hx3, 49)\n setup(hx4, 44)\n\n try:\n tty.setcbreak(sys.stdin.fileno())\n\n i = 0\n is_writing = False\n print('s: Straight')\n print('f: Forward')\n print('b: Backward')\n print('l: Left')\n print('r: Right')\n print('z: Cross Left')\n print('x Cross Right')\n print('y: Start writing')\n print('p: Pause writing')\n print('esc: Exit')\n first_write = False\n while True:\n if isData():\n c = sys.stdin.read(1)\n \n if c == 's':\n label = 'Straight'\n elif c == 'f':\n label = 'Forward'\n elif c == 'b':\n label = 'Backward'\n elif c == 'l':\n label = 'Left'\n elif c == 'r':\n label = 'Right'\n elif c == 'z':\n label = 'Cross Left'\n elif c == 'x':\n label = 'Cross Right'\n elif c == 'n':\n label = 'Not Sitting'\n elif c == 'p':\n # Stop writing\n is_writing = False\n elif c == 'y':\n is_writing = True\n first_write = True\n # Start writing\n print(c)\n print(label)\n elif is_writing:\n\n file_path = '/home/pi/Documents/data/' + subject + '.csv'\n\n if os.path.isfile(file_path) and data is None:\n print('Reading from old file')\n data = pd.read_csv(file_path)\n elif data is None:\n fieldnames = ['Load Cell 1', 'Load Cell 2', 'Load Cell 3', 'Load Cell 4', 'Total', 'Subject', 'Class']\n data = pd.DataFrame(columns=fieldnames)\n\n try:\n scale_num = 0\n sum_ = 0\n row = {}\n for hx in [hx1, hx2, hx3, hx4]:\n #for i in range(1,5):\n scale_num += 1\n val = 6\n val = hx.get_weight(5)\n sum_ += val\n row['Load Cell ' + str(scale_num)] = val\n print('Load Cell # {}: {}'.format(scale_num, val))\n\n row['Total'] = sum_\n row['Subject'] = subject\n row['Class'] = label\n data = data.append(row, ignore_index=True)\n\n print('total {}'.format(sum_))\n\n\n\n hx1.power_down()\n hx1.power_up()\n hx2.power_down()\n hx2.power_up()\n hx3.power_down()\n hx3.power_up()\n hx4.power_down()\n hx4.power_up()\n time.sleep(1)\n\n except (KeyboardInterrupt, SystemExit):\n data.to_csv(file_path, index=False)\n cleanAndExit()\n finally:\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)\n\n\n\n","sub_path":"keyboard_input.py","file_name":"keyboard_input.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"322576732","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 1 15:29:29 2016\n\n@author: Chandler\n\"\"\"\nimport pandas as pd \nimport numpy as np \nimport dateutil.relativedelta\npd.options.mode.chained_assignment = None # default='warn'\n\ndef Merge_Orig_Perf(df_orig, df_perf):\n\tdf_orig_temp = df_orig[['loan_seq_number', 'original_interest_rate', 'original_upb']]\n\tdf_orig_temp.rename(columns={'original_interest_rate':'current_interest_rate'}, inplace=True)\n\tdf_orig_temp.rename(columns={'original_upb':'current_actual_upb'}, inplace=True)\n\n\tdf_merged = pd.concat([df_perf, df_orig_temp])\n\tdf_merged['reporting_period'] = pd.to_datetime(df_merged['reporting_period'], format='%m/%d/%Y',\n\t\t\t\t\t\t\t\t\t\t\t\t errors='ignore')\n\tdf_merged['loan_age'].fillna(-1, inplace=True)\n\tdf_merged.sort_values(by=['loan_seq_number', 'loan_age'], ascending=[True,True], \n\t\t\t\t\t\tinplace=True)\n\tdf_merged.fillna(np.nan, inplace=True)\n\t#df_merged.to_csv('freddie_merged.csv', index=False)\n\n\treturn df_merged\n\ndef Remove_Missing_Principal_Bonds(df_merged, df_orig):\n\t\"\"\"\n\t\tBonds who were missing current principal balance midway through.\n\t\"\"\"\n\tdf_merged.set_index('loan_seq_number', inplace=True)\n\tdf_orig.set_index('loan_seq_number', inplace=True)\n\tindex_to_drop = df_merged[df_merged['current_actual_upb'] == 'nan'].index\n\tdf_merged.drop(index_to_drop, inplace=True)\n\tdf_orig.drop(index_to_drop, inplace=True)\n\tdf_merged.reset_index(level=0, inplace=True)\t# reset 'loan_seq_number' to column\n\tdf_orig.reset_index(level=0, inplace=True)\t# reset 'loan_seq_number' to column\n\n\treturn df_merged, df_orig\n\ndef Create_Pay_Cols(df_mtx):\n\t\"\"\"\n\t\tColumns: [0:'loan_seq_number', 1:'current_actual_upb', 2:'current_interest_rate',\n\t\t\t\t 3:'delinquency_status', 4:'loan_age', 5:'remaining_months_to_maturity',\n\t\t\t\t 6:'reporting_period']\n\t\"\"\"\n\t# columns added\n\tcols_added = ['Principal+Interest Paid', 'Interest Paid','Principal Paid', \n\t\t\t\t 'Principal+Prepayment Paid', 'Prepayment Paid']\n\n\t# convert interest rate to monthly decimals\n\tdf_mtx[:, 2] = df_mtx[:, 2] / 100.0 / 12.0\n\n\tint_pay_arr = [0] * df_mtx.shape[0]\n\tamort_pay_arr = [0] * df_mtx.shape[0]\n\tprinc_arr = [0] * df_mtx.shape[0]\n\tprinc_and_ppy_arr = [0] * df_mtx.shape[0]\n\tprepay_arr = [0] * df_mtx.shape[0]\n\n\tfor i in range(df_mtx.shape[0]):\n\t\tif df_mtx[i, 5] == 'nan':\t# remaining_months_to_maturity\n\t\t\t#df_mtx[i, 5] = int(df_mtx[i+1, 5]) + 1\t# fill in original r_m_t_m\n\t\t\tpass\n\t\telse:\n\t\t\tint_pay_arr[i] = df_mtx[i-1, 1] * df_mtx[i, 2]\t# 'interest_paid' column\n\t\t\tamort_pay_arr[i] = (-1)*np.pmt(df_mtx[i, 2], df_mtx[i, 5], df_mtx[i-1, 1])\n\t\t\tprinc_arr[i] = amort_pay_arr[i] - int_pay_arr[i]\n\t\t\tprinc_and_ppy_arr[i] = df_mtx[i-1, 1] - df_mtx[i, 1]\n\t\t\tprepay_arr[i] = princ_and_ppy_arr[i] - princ_arr[i]\n\n\tdf_new_mtx = np.column_stack([df_mtx, amort_pay_arr, int_pay_arr, princ_arr, \n\t\t\t\t\t\t\t\t princ_and_ppy_arr, prepay_arr])\n\n\treturn df_new_mtx, cols_added\n\ndef Calc_Prepay_Percent(df, df_orig):\n\t\"\"\"\n\t\tGroup performance data by 'loan_seq_number'.\n\t\tTake sum of all prepayments, including negative prepayemnts.\n\t\tDivide original loan amount by sum of prepayments to get prepayment %.\n\t\"\"\"\n\tgrouped = df.groupby('loan_seq_number')\n\tprepay_percent_arr = []\n\n\tfor name, group in grouped:\n\t\tprepay_percent_arr.append(\n\t\t\t[name, group['Prepayment Paid'].sum() / group['current_actual_upb'].max()])\n\n\tprepay_percent_arr = np.array(prepay_percent_arr)\n\tdf_orig['Prepay Percent'] = prepay_percent_arr[:,1]\n\n\treturn df_orig\ndef Revise_format(df_orig):\n '''\n Change first_time_homebuyer_flag and prepayment_penalty_flag into dummy variable, change ltv and int rate into decimal number\n '''\n for i in range(len(df_orig['first_time_homebuyer_flag'])):\n df_orig['first_time_homebuyer_flag'][i] = 1 if df_orig['first_time_homebuyer_flag'][i] == 'Y' else 0\n df_orig['prepayment_penalty_flag'][i] = 1 if df_orig['prepayment_penalty_flag'][i] == 'Y' else 0 \n df_orig['original_combined_ltv'] = df_orig['original_combined_ltv']/100\n df_orig['original_interest_rate'] = df_orig['original_interest_rate']/100\n df_orig['original_ltv'] = df_orig['original_ltv']/100\n df_orig['mortgage_insurance_percentage'] = df_orig['mortgage_insurance_percentage']/100\n return df_orig","sub_path":"clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"372383749","text":"import sys\nimport os\nimport time\nimport logging\nimport datetime\n\nfrom elasticsearch import ElasticsearchConsumer\nfrom neo4j_connector import Neo4jConnector\n\nlogger = logging.getLogger('ingestor')\n\n\nclass Ingestor(object):\n def __init__(self):\n # Load env vars and compute index names\n logger.info(\"Initialising ingestor\")\n self._parse_config()\n self._compute_indexes()\n\n # Instantiate clients\n logger.info(\"Instantiating clients\")\n self.db = Neo4jConnector()\n self._es_init_clients()\n\n def _parse_config(self):\n \"\"\"\n Fetch the connection string from environment variables:\n\n ELASTIC_URL: The URI of ElasticSearch\n ELASTICSEARCH_USER: Username for ElasticSearch\n ELASTICSEARCH_PASSWORD: Password for ElasticSearch\n ELASTIC_INDEX: ElasticSearch index\n ELASTIC_DRY_RUN: Whether if the ingestion is real or dry-run only\n ES_INDEX_SPEC: Index specification (path to json file)\n \"\"\"\n self.elastic_url = os.environ['ELASTIC_URL']\n self._elastic_user = os.environ['ELASTICSEARCH_USER']\n self._elastic_password = os.environ['ELASTICSEARCH_PASSWORD']\n self.elastic_index = os.environ['ELASTIC_INDEX']\n self.elastic_dry_run = os.environ['ELASTIC_DRY_RUN']\n self.es_index_spec = os.environ['ES_INDEX_SPEC']\n\n def _compute_indexes(self):\n # Compute tag to identify this run\n now = datetime.datetime.now()\n self.run_tag = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n # Define indexes\n self.index_standard = self.elastic_index\n self.index_short_term = \"short-term-{}\".format(self.elastic_index)\n\n # ==========================================================================\n # ES INTEGRATION\n # ==========================================================================\n def _es_init_clients(self):\n \"\"\"\n Instantiate one ES client for each index to be used:\n cartography-
\n short-term-cartography-\n \"\"\"\n self.es_clients = []\n for index in [self.index_standard, self.index_short_term]:\n c = ElasticsearchConsumer(\n self.elastic_url,\n index,\n self.elastic_dry_run,\n self.elastic_user,\n self.elastic_password,\n )\n self.es_clients.append(c)\n\n def _es_push_indexes(self, content):\n \"\"\"\n For each ES client, create an index for today's ingestion\n \"\"\"\n for c in self.es_clients:\n c.create_index(content)\n\n def _es_push_results(self, query_name, records):\n \"\"\"\n For each ES client, push the records provided\n \"\"\"\n for c in self.es_clients:\n c.send_to_es(query_name, records)\n\n # ==========================================================================\n # RECORD MANIPULATION\n # ==========================================================================\n def _sanitise_fields(self, record):\n \"\"\"\n ElasticSearch doesn't like parenthesis in the field names,\n so we have to replace them before ingesting the records.\n \"\"\"\n sanitised = {}\n for k, v in record.items():\n new_key = k.replace('(', '_').replace(')', '_')\n sanitised[new_key] = v\n return sanitised\n\n def _enrich_results(self, record, query):\n \"\"\"\n Enrich results from Neo4j with metadata needed by ES\n \"\"\"\n record['metadata.query_name'] = query['name']\n record['metadata.query_id'] = '{}_{}'.format(query['name'], self.run_tag)\n record['metadata.query_description'] = query['description']\n record['metadata.query_headers'] = query['headers']\n record['@timestamp'] = int(round(time.time() * 1000))\n return record\n\n # ==========================================================================\n # EXPOSED OPERATIONS\n # ==========================================================================\n def push_indexes(self):\n with open(self.es_index_spec) as fp:\n content = fp.read()\n self._es_push_indexes(content)\n\n def query_by_tag(self, tags):\n logger.info(\"Querying Neo4J by tags: {}\".format(tags))\n return self.db.query_by_tag(tags)\n\n def push_results(self, queries_results):\n logger.info(\"Pushing query results to ES\")\n for query in queries_results:\n # query = {\n # 'name': 'gcp_project_list',\n # 'description': 'Full list of GCPProjects',\n # 'headers': ['project_id', ...],\n # 'result': [ {...}, ]\n for r in query['result']:\n # Sanitise fields\n sanitised = self._sanitise_fields(r)\n # Enrich data\n enriched = self._enrich_results(sanitised, query)\n # Send to elastic\n self._es_push_results(query['name'], enriched)\n\n\ndef main():\n # Instantiate ingestor\n ingestor = Ingestor()\n\n # Define index\n logger.info(\"Pushing Elasticsearch indexes...\")\n ingestor.push_indexes()\n\n logger.info(\"Starting ingesting data from Neo4j...\")\n\n # Queries - AWS\n queries_results = ingestor.query_by_tag(['cloud', 'aws'])\n ingestor.push_results(queries_results)\n\n # Queries - GCP\n queries_results = ingestor.query_by_tag(['cloud', 'gcp'])\n ingestor.push_results(queries_results)\n\n logger.info(\"Ingestion completed successfully\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"consumers/elasticsearch/deployment/py/ingestor.py","file_name":"ingestor.py","file_ext":"py","file_size_in_byte":5581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"626928159","text":"# -*- coding: utf-8 -*-\n\"\"\"Basic raspa output parser.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport re\n\nfrom math import isnan, isinf\nfrom six.moves import range\nfrom six.moves import zip\n\nfloat_base = float # pylint: disable=invalid-name\n\n\ndef float(number): # pylint: disable=redefined-builtin\n number = float_base(number)\n return number if not any((isnan(number), isinf(number))) else None\n\n\nKELVIN_TO_KJ_PER_MOL = float(8.314464919 / 1000.0) #exactly the same as Raspa\n\n# manage block of the first type\n# --------------------------------------------------------------------------------------------\nBLOCK_1_LIST = [\n (re.compile(\"Average Volume:\"), \"cell_volume\", (1, 2, 4), 0),\n (re.compile(\"Average Pressure:\"), \"pressure\", (1, 2, 4), 0),\n (re.compile(\"Average temperature:\"), \"temperature\", (1, 2, 4), 0),\n (re.compile(\"Average Density:\"), \"adsorbate_density\", (1, 2, 4), 0),\n (re.compile(\"Total energy:$\"), \"total_energy\", (1, 2, 4), 0),\n (re.compile(\"Average Heat Capacity\"), \"framework_heat_capacity\", (1, 2, 4), 0),\n (re.compile(\"Heat of desorption:\"), \"heat_of_desorption\", (1, 4, 3), 4),\n (re.compile(\"Enthalpy of adsorption:\"), \"enthalpy_of_adsorption\", (1, 4, 3), 4),\n (re.compile(\".*Total enthalpy of adsorption from components and measured mol-fraction\"),\n \"enthalpy_of_adsorption_total_molfrac\", (1, 4, 3), 0),\n]\n\n# block of box properties.\nBOX_PROP_LIST = [\n (re.compile(\"Average Box-lengths:\"), 'box'),\n]\n\n\n# pylint: disable=too-many-arguments\ndef parse_block1(flines, result_dict, prop, value=1, unit=2, dev=4):\n \"\"\"Parse block that looks as follows:\n Average Volume:\n =================\n Block[ 0] 12025.61229 [A^3]\n Block[ 1] 12025.61229 [A^3]\n Block[ 2] 12025.61229 [A^3]\n Block[ 3] 12025.61229 [A^3]\n Block[ 4] 12025.61229 [A^3]\n ------------------------------------------------------------------------------\n Average 12025.61229 [A^3] +/- 0.00000 [A^3]\n \"\"\"\n for line in flines:\n if 'Average' in line:\n result_dict[prop + '_average'] = float(line.split()[value])\n result_dict[prop + '_unit'] = re.sub(r\"[{}()\\[\\]]\", '', line.split()[unit])\n result_dict[prop + '_dev'] = float(line.split()[dev])\n break\n\n\n# manage energy block\n# --------------------------------------------------------------------------------------------\nENERGY_BLOCK_LIST = [\n (re.compile(\"Average Adsorbate-Adsorbate energy:\"), 'ads_ads'),\n (re.compile(\"Average Host-Adsorbate energy:\"), 'host_ads'),\n]\n\n\ndef parse_block_energy(flines, res_dict, prop):\n \"\"\"Parse block that looks as follows:\n Average Adsorbate-Adsorbate energy:\n ===================================\n Block[ 0] -443.23204 Van der Waals: -443.23204 Coulomb: 0.00000 [K]\n Block[ 1] -588.20205 Van der Waals: -588.20205 Coulomb: 0.00000 [K]\n Block[ 2] -538.43355 Van der Waals: -538.43355 Coulomb: 0.00000 [K]\n Block[ 3] -530.00960 Van der Waals: -530.00960 Coulomb: 0.00000 [K]\n Block[ 4] -484.15106 Van der Waals: -484.15106 Coulomb: 0.00000 [K]\n ------------------------------------------------------------------------------\n Average -516.80566 Van der Waals: -516.805659 Coulomb: 0.00000 [K]\n +/- 98.86943 +/- 98.869430 +/- 0.00000 [K]\n \"\"\"\n for line in flines:\n if 'Average' in line:\n res_dict[prop + '_total_energy_unit'] = 'kJ/mol'\n res_dict[prop + '_vdw_energy_unit'] = 'kJ/mol'\n res_dict[prop + '_coulomb_energy_unit'] = 'kJ/mol'\n res_dict[prop + '_total_energy_average'] = float(line.split()[1]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_vdw_energy_average'] = float(line.split()[5]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_coulomb_energy_average'] = float(line.split()[7]) * KELVIN_TO_KJ_PER_MOL\n if '+/-' in line:\n res_dict[prop + '_total_energy_dev'] = float(line.split()[1]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_vdw_energy_dev'] = float(line.split()[3]) * KELVIN_TO_KJ_PER_MOL\n res_dict[prop + '_coulomb_energy_dev'] = float(line.split()[5]) * KELVIN_TO_KJ_PER_MOL\n return\n\n\n# manage lines with components\n# --------------------------------------------------------------------------------------------\nLINES_WITH_COMPONENT_LIST = [\n (re.compile(\" Average chemical potential: \"), \"chemical_potential\"),\n (re.compile(\" Average Henry coefficient: \"), \"henry_coefficient\"),\n (re.compile(\" Average _1-_0:\"), \"adsorption_energy_widom\"),\n (re.compile(\" Average Widom Rosenbluth-weight:\"), \"widom_rosenbluth_factor\"),\n]\n\n\ndef parse_lines_with_component(res_components, components, line, prop):\n \"\"\"Parse lines that contain components\"\"\"\n # self.logger.info(\"analysing line: {}\".format(line))\n for i, component in enumerate(components):\n if '[' + component + ']' in line:\n words = line.split()\n res_components[i][prop + '_unit'] = re.sub(r'[{}()\\[\\]]', '', words[-1])\n res_components[i][prop + '_dev'] = float(words[-2])\n res_components[i][prop + '_average'] = float(words[-4])\n\n\n# pylint: disable=too-many-locals, too-many-arguments, too-many-statements, too-many-branches\ndef parse_base_output(output_abs_path, system_name, ncomponents):\n \"\"\"Parse RASPA output file\"\"\"\n\n warnings = []\n res_per_component = []\n for i in range(ncomponents):\n res_per_component.append({})\n result_dict = {'exceeded_walltime': False}\n framework_density = re.compile(\"Framework Density:\")\n num_of_molec = re.compile(\"Number of molecules:$\")\n\n with open(output_abs_path, \"r\") as fobj:\n # 1st parsing part\n icomponent = 0\n component_names = []\n res_cmp = res_per_component[0]\n for line in fobj:\n if \"Component\" in line and \"(Adsorbate molecule)\" in line:\n component_names.append(line.split()[2][1:-1])\n # Consider to change it with parse_line()\n if \"Conversion factor molecules/unit cell -> mol/kg:\" in line:\n res_cmp['conversion_factor_molec_uc_to_mol_kg'] = float(line.split()[6])\n res_cmp['conversion_factor_molec_uc_to_mol_kg_unit'] = \"(mol/kg)/(molec/uc)\"\n # this line was corrected in Raspa's commit c1ad4de (Nov19), since \"gr/gr\" should read \"mg/g\"\n if \"Conversion factor molecules/unit cell -> gr/gr:\" in line \\\n or \"Conversion factor molecules/unit cell -> mg/g:\" in line:\n res_cmp['conversion_factor_molec_uc_to_mg_g'] = float(line.split()[6])\n res_cmp['conversion_factor_molec_uc_to_mg_g_unit'] = \"(mg/g)/(molec/uc)\"\n if \"Conversion factor molecules/unit cell -> cm^3 STP/gr:\" in line:\n res_cmp['conversion_factor_molec_uc_to_cm3stp_gr'] = float(line.split()[7])\n res_cmp['conversion_factor_molec_uc_to_cm3stp_gr_unit'] = \"(cm^3_STP/gr)/(molec/uc)\"\n if \"Conversion factor molecules/unit cell -> cm^3 STP/cm^3:\" in line:\n res_cmp['conversion_factor_molec_uc_to_cm3stp_cm3'] = float(line.split()[7])\n res_cmp['conversion_factor_molec_uc_to_cm3stp_cm3_unit'] = \"(cm^3_STP/cm^3)/(molec/uc)\"\n if \"MolFraction:\" in line:\n res_cmp['mol_fraction'] = float(line.split()[1])\n res_cmp['mol_fraction_unit'] = \"-\"\n if \"Partial pressure:\" in line:\n res_cmp['partial_pressure'] = float(line.split()[2])\n res_cmp['partial_pressure_unit'] = \"Pa\"\n if \"Partial fugacity:\" in line:\n res_cmp['partial_fugacity'] = float(line.split()[2])\n res_cmp['partial_fugacity_unit'] = \"Pa\"\n icomponent += 1\n if icomponent < ncomponents:\n res_cmp = res_per_component[icomponent]\n else:\n break\n # end of the 1st parsing part\n\n # 2nd parsing part\n for line in fobj:\n for parse in BLOCK_1_LIST:\n if parse[0].match(line):\n parse_block1(fobj, result_dict, parse[1], *parse[2])\n # I assume here that properties per component are present furhter in the output file.\n # so I need to skip some lines:\n skip_nlines_after = parse[3]\n while skip_nlines_after > 0:\n line = next(fobj)\n skip_nlines_after -= 1\n for i, cmpnt in enumerate(component_names):\n # The order of properties per molecule is the same as the order of molecules in the\n # input file. So if component name was not found in the next line, I break the loop\n # immidiately as there is no reason to continue it\n line = next(fobj)\n if cmpnt in line:\n parse_block1(fobj, res_per_component[i], parse[1], *parse[2])\n else:\n break\n skip_nlines_after = parse[3]\n while skip_nlines_after > 0:\n line = next(fobj)\n skip_nlines_after -= 1\n\n continue # no need to perform further checks, propperty has been found already\n for parse in ENERGY_BLOCK_LIST:\n if parse[0].match(line):\n parse_block_energy(fobj, result_dict, prop=parse[1])\n continue # no need to perform further checks, propperty has been found already\n for parse in BOX_PROP_LIST:\n if parse[0].match(line):\n # parse three cell vectors\n parse_block1(fobj, result_dict, prop='box_ax', value=2, unit=3, dev=5)\n parse_block1(fobj, result_dict, prop='box_by', value=2, unit=3, dev=5)\n parse_block1(fobj, result_dict, prop='box_cz', value=2, unit=3, dev=5)\n # parsee angles between the cell vectors\n parse_block1(fobj, result_dict, prop='box_alpha', value=3, unit=4, dev=6)\n parse_block1(fobj, result_dict, prop='box_beta', value=3, unit=4, dev=6)\n parse_block1(fobj, result_dict, prop='box_gamma', value=3, unit=4, dev=6)\n if framework_density.match(line) is not None:\n result_dict['framework_density'] = line.split()[2]\n result_dict['framework_density_unit'] = re.sub(r'[{}()\\[\\]]', '', line.split()[3])\n\n elif num_of_molec.match(line) is not None:\n break # this stops the cycle\n # end of the 2nd parsing part\n\n # 3rd parsing part\n icomponent = 0\n for line in fobj:\n # Consider to change it with parse_line?\n if 'Average loading absolute [molecules/unit cell]' in line:\n res_per_component[icomponent]['loading_absolute_average'] = float(line.split()[5])\n res_per_component[icomponent]['loading_absolute_dev'] = float(line.split()[7])\n res_per_component[icomponent]['loading_absolute_unit'] = 'molecules/unit cell'\n elif 'Average loading excess [molecules/unit cell]' in line:\n res_per_component[icomponent]['loading_excess_average'] = float(line.split()[5])\n res_per_component[icomponent]['loading_excess_dev'] = float(line.split()[7])\n res_per_component[icomponent]['loading_excess_unit'] = 'molecules/unit cell'\n icomponent += 1\n if icomponent >= ncomponents:\n break\n # end of the 3rd parsing part\n\n # 4th parsing part\n for line in fobj:\n for to_parse in LINES_WITH_COMPONENT_LIST:\n if to_parse[0].search(line):\n parse_lines_with_component(res_per_component, component_names, line, to_parse[1])\n # end of the 4th parsing part\n\n return_dictionary = {\"general\": result_dict, \"components\": {}}\n\n for name, value in zip(component_names, res_per_component):\n return_dictionary[\"components\"][name] = value\n\n with open(output_abs_path, \"r\") as fobj:\n for line in fobj:\n if \"WARNING\" in line:\n warnings.append((system_name, line))\n return return_dictionary, warnings\n","sub_path":"aiida_raspa/utils/base_parser.py","file_name":"base_parser.py","file_ext":"py","file_size_in_byte":12776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"70016444","text":"import pytest\n\nfrom django.urls import reverse\n\n\n@pytest.fixture(autouse=True)\ndef setup(mock_cases_search, authorized_client, queue_pk, mock_queue, mock_countries):\n yield\n\n\n@pytest.mark.parametrize(\n \"url\",\n [\n reverse(\"core:index\"),\n reverse(\"queues:cases\"),\n reverse(\"queues:cases\", kwargs={\"queue_pk\": \"00000000-0000-0000-0000-000000000001\"}),\n ],\n)\ndef test_cases_view(url, authorized_client):\n response = authorized_client.get(url)\n assert response.status_code == 200\n","sub_path":"unit_tests/caseworker/queues/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"511954193","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport xlrd\nimport xlsxwriter\nfrom tqdm import tqdm\n\n\ndef find_miss_post(filepath):\n filename_list = []\n for file in os.listdir(filepath):\n if file.endswith('xlsx'):\n filename_list.append(int(file.split('.')[0]))\n filename_list.sort()\n max_post = filename_list[-1]\n for ele in range(0, max_post):\n if (ele+1) not in filename_list:\n print(str(ele)+' is not exist')\n\n\n# 获取目录下的所有文件名\ndef get_filename(tar_path):\n filename_list = []\n for file in os.listdir(tar_path):\n if file.endswith('xlsx'):\n filename_list.append(int(file.split('.')[0]))\n filename_list.sort()\n filename = []\n for file in filename_list:\n filename.append(tar_path+'/'+str(file)+'.xlsx')\n return filename\n\n\ndef concat_and_insert(f_dir):\n records = []\n print('read xlsx')\n for ai in tqdm(f_dir):\n # 读文件\n data = xlrd.open_workbook(ai)\n # 第一个sheet页的名称\n first_sheet = data.sheet_by_index(0).name\n # print(ai, '>'*10, first_sheet)\n # 获取sheet页的名称\n sheet = data.sheet_by_name(first_sheet)\n # 获取表的行数\n n_rows = sheet.nrows\n if n_rows == 0:\n print(ai+' is empty')\n for i in range(n_rows):\n records.append(sheet.row_values(i))\n return records\n\n\ndef write_file(alist, tar_name):\n tarfile = tar_name + '.xlsx'\n print('write '+tarfile)\n w_new = xlsxwriter.Workbook(tarfile)\n w_add = w_new.add_worksheet(tar_name)\n for row_num, row_data in enumerate(alist):\n w_add.write_row(row_num, 0, row_data)\n w_new.close()\n\n\nif __name__ == '__main__':\n file_path = sys.argv[1]\n\n find_miss_post(file_path)\n\n file_name = get_filename(file_path)\n\n records_all = concat_and_insert(file_name)\n\n tarname = file_path\n write_file(records_all, tarname)\n","sub_path":"each_xlsx_to_one.py","file_name":"each_xlsx_to_one.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"590370906","text":"# encoding: utf-8\n\n\"\"\"\nTest suite for pptx.shapes.shape module\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport pytest\n\nfrom pptx.oxml.shapes.shared import BaseShapeElement\nfrom pptx.oxml.text import CT_TextBody\nfrom pptx.parts.slide import _SlideShapeTree\nfrom pptx.shapes import Subshape\nfrom pptx.shapes.shape import BaseShape\nfrom pptx.text import TextFrame\n\nfrom ..oxml.unitdata.shape import (\n a_cxnSp, a_graphicFrame, a_grpSp, a_grpSpPr, a_p_xfrm, a_pic, an_ext,\n an_off, an_sp, an_spPr, an_xfrm\n)\nfrom ..unitutil import class_mock, instance_mock, loose_mock, property_mock\n\n\nclass DescribeBaseShape(object):\n\n def it_knows_its_shape_id(self, id_fixture):\n shape, shape_id = id_fixture\n assert shape.id == shape_id\n\n def it_knows_its_name(self, name_fixture):\n shape, name = name_fixture\n assert shape.name == name\n\n def it_has_a_position(self, position_get_fixture):\n shape, expected_left, expected_top = position_get_fixture\n assert shape.left == expected_left\n assert shape.top == expected_top\n\n def it_has_dimensions(self, dimensions_get_fixture):\n shape, expected_width, expected_height = dimensions_get_fixture\n assert shape.width == expected_width\n assert shape.height == expected_height\n\n def it_can_change_its_position(self, position_set_fixture):\n shape, left, top, expected_xml = position_set_fixture\n shape.left = left\n shape.top = top\n assert shape._element.xml == expected_xml\n\n def it_can_change_its_dimensions(self, dimensions_set_fixture):\n shape, width, height, expected_xml = dimensions_set_fixture\n shape.width = width\n shape.height = height\n assert shape._element.xml == expected_xml\n\n def it_knows_the_part_it_belongs_to(self, part_fixture):\n shape, parent_ = part_fixture\n part = shape.part\n assert part is parent_.part\n\n def it_knows_whether_it_can_contain_text(self, has_textframe_fixture):\n shape, has_textframe = has_textframe_fixture\n assert shape.has_textframe is has_textframe\n\n def it_knows_whether_it_is_a_placeholder(self, is_placeholder_fixture):\n shape, is_placeholder = is_placeholder_fixture\n assert shape.is_placeholder is is_placeholder\n\n def it_provides_access_to_its_textframe(self, textframe_fixture):\n shape, TextFrame_, txBody_, textframe_ = textframe_fixture\n textframe = shape.textframe\n TextFrame_.assert_called_once_with(txBody_, shape)\n assert textframe is textframe_\n\n def it_raises_when_no_textframe(self, no_textframe_fixture):\n shape = no_textframe_fixture\n with pytest.raises(ValueError):\n shape.textframe\n\n def it_can_set_the_shape_text_to_a_string(self, text_set_fixture):\n shape = text_set_fixture\n shape.text = 'føøbår'\n assert shape.textframe.text == u'føøbår'\n\n def it_raises_on_assign_text_where_no_textframe(\n self, no_textframe_fixture):\n shape = no_textframe_fixture\n with pytest.raises(TypeError):\n shape.text = 'foobar'\n\n # fixtures -------------------------------------------------------\n\n @pytest.fixture(params=[\n ('sp', False), ('sp_with_ext', True),\n ('pic', False), ('pic_with_ext', True),\n ('graphicFrame', False), ('graphicFrame_with_ext', True),\n ('grpSp', False), ('grpSp_with_ext', True),\n ('cxnSp', False), ('cxnSp_with_ext', True),\n ])\n def dimensions_get_fixture(self, request, width, height):\n shape_elm_fixt_name, expect_values = request.param\n shape_elm = request.getfuncargvalue(shape_elm_fixt_name)\n shape = BaseShape(shape_elm, None)\n if not expect_values:\n width = height = None\n return shape, width, height\n\n @pytest.fixture(params=[\n ('sp', 'sp_with_ext'),\n ('pic', 'pic_with_ext'),\n ('graphicFrame', 'graphicFrame_with_ext'),\n ('grpSp', 'grpSp_with_ext'),\n ('cxnSp', 'cxnSp_with_ext'),\n ])\n def dimensions_set_fixture(self, request, width, height):\n start_elm_fixt_name, expected_elm_fixt_name = request.param\n start_elm = request.getfuncargvalue(start_elm_fixt_name)\n shape = BaseShape(start_elm, None)\n expected_xml = request.getfuncargvalue(expected_elm_fixt_name).xml\n return shape, width, height, expected_xml\n\n @pytest.fixture\n def id_fixture(self, shape_elm_, shape_id):\n shape = BaseShape(shape_elm_, None)\n return shape, shape_id\n\n @pytest.fixture(params=[True, False])\n def has_textframe_fixture(self, request, shape_elm_, txBody_):\n has_textframe = request.param\n shape_elm_.txBody = txBody_ if has_textframe else None\n shape = BaseShape(shape_elm_, None)\n return shape, has_textframe\n\n @pytest.fixture(params=[True, False])\n def is_placeholder_fixture(self, request, shape_elm_, txBody_):\n is_placeholder = request.param\n shape_elm_.has_ph_elm = is_placeholder\n shape = BaseShape(shape_elm_, None)\n return shape, is_placeholder\n\n @pytest.fixture\n def name_fixture(self, shape_elm_, shape_name):\n shape = BaseShape(shape_elm_, None)\n return shape, shape_name\n\n @pytest.fixture\n def no_textframe_fixture(self, shape_elm_):\n shape_elm_.txBody = None\n shape = BaseShape(shape_elm_, None)\n return shape\n\n @pytest.fixture\n def part_fixture(self, shapes_):\n parent_ = shapes_\n shape = BaseShape(None, parent_)\n return shape, parent_\n\n @pytest.fixture(params=[\n ('sp', False), ('sp_with_off', True),\n ('pic', False), ('pic_with_off', True),\n ('graphicFrame', False), ('graphicFrame_with_off', True),\n ('grpSp', False), ('grpSp_with_off', True),\n ('cxnSp', False), ('cxnSp_with_off', True),\n ])\n def position_get_fixture(self, request, left, top):\n shape_elm_fixt_name, expect_values = request.param\n shape_elm = request.getfuncargvalue(shape_elm_fixt_name)\n shape = BaseShape(shape_elm, None)\n if not expect_values:\n left = top = None\n return shape, left, top\n\n @pytest.fixture(params=[\n ('sp', 'sp_with_off'),\n ('pic', 'pic_with_off'),\n ('graphicFrame', 'graphicFrame_with_off'),\n ('grpSp', 'grpSp_with_off'),\n ('cxnSp', 'cxnSp_with_off'),\n ])\n def position_set_fixture(self, request, left, top):\n start_elm_fixt_name, expected_elm_fixt_name = request.param\n start_elm = request.getfuncargvalue(start_elm_fixt_name)\n shape = BaseShape(start_elm, None)\n expected_xml = request.getfuncargvalue(expected_elm_fixt_name).xml\n return shape, left, top, expected_xml\n\n @pytest.fixture\n def textframe_fixture(self, shape_elm_, TextFrame_, txBody_, textframe_):\n shape = BaseShape(shape_elm_, None)\n return shape, TextFrame_, txBody_, textframe_\n\n @pytest.fixture\n def text_set_fixture(self, shape_elm_, shape_textframe_):\n shape = BaseShape(shape_elm_, None)\n return shape\n\n # fixture components ---------------------------------------------\n\n @pytest.fixture\n def cxnSp(self):\n return a_cxnSp().with_nsdecls().with_child(an_spPr()).element\n\n @pytest.fixture\n def cxnSp_with_ext(self, width, height):\n return (\n a_cxnSp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def cxnSp_with_off(self, left, top):\n return (\n a_cxnSp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def graphicFrame(self):\n # Note that element is required on graphicFrame\n return a_graphicFrame().with_nsdecls().with_child(a_p_xfrm()).element\n\n @pytest.fixture\n def graphicFrame_with_ext(self, width, height):\n return (\n a_graphicFrame().with_nsdecls().with_child(\n a_p_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height)))\n ).element\n\n @pytest.fixture\n def graphicFrame_with_off(self, left, top):\n return (\n a_graphicFrame().with_nsdecls().with_child(\n a_p_xfrm().with_child(\n an_off().with_x(left).with_y(top)))\n ).element\n\n @pytest.fixture\n def grpSp(self):\n return (\n a_grpSp().with_nsdecls('p', 'a').with_child(\n a_grpSpPr())\n ).element\n\n @pytest.fixture\n def grpSp_with_ext(self, width, height):\n return (\n a_grpSp().with_nsdecls('p', 'a').with_child(\n a_grpSpPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def grpSp_with_off(self, left, top):\n return (\n a_grpSp().with_nsdecls('p', 'a').with_child(\n a_grpSpPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def height(self):\n return 654\n\n @pytest.fixture\n def left(self):\n return 123\n\n @pytest.fixture\n def pic(self):\n return a_pic().with_nsdecls().with_child(an_spPr()).element\n\n @pytest.fixture\n def pic_with_off(self, left, top):\n return (\n a_pic().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def pic_with_ext(self, width, height):\n return (\n a_pic().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def shape_elm_(self, request, shape_id, shape_name, txBody_):\n return instance_mock(\n request, BaseShapeElement, shape_id=shape_id,\n shape_name=shape_name, txBody=txBody_\n )\n\n @pytest.fixture\n def shape_id(self):\n return 42\n\n @pytest.fixture\n def shape_name(self):\n return 'Foobar 41'\n\n @pytest.fixture\n def shape_textframe_(self, request):\n return property_mock(request, BaseShape, 'textframe')\n\n @pytest.fixture\n def shapes_(self, request):\n return instance_mock(request, _SlideShapeTree)\n\n @pytest.fixture\n def sp(self):\n return an_sp().with_nsdecls().with_child(an_spPr()).element\n\n @pytest.fixture\n def sp_with_ext(self, width, height):\n return (\n an_sp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_ext().with_cx(width).with_cy(height))))\n ).element\n\n @pytest.fixture\n def sp_with_off(self, left, top):\n return (\n an_sp().with_nsdecls().with_child(\n an_spPr().with_child(\n an_xfrm().with_child(\n an_off().with_x(left).with_y(top))))\n ).element\n\n @pytest.fixture\n def TextFrame_(self, request, textframe_):\n return class_mock(\n request, 'pptx.shapes.shape.TextFrame', return_value=textframe_\n )\n\n @pytest.fixture\n def textframe_(self, request):\n return instance_mock(request, TextFrame)\n\n @pytest.fixture\n def top(self):\n return 456\n\n @pytest.fixture\n def txBody_(self, request):\n return instance_mock(request, CT_TextBody)\n\n @pytest.fixture\n def width(self):\n return 321\n\n\nclass DescribeSubshape(object):\n\n def it_knows_the_part_it_belongs_to(self, subshape_with_parent_):\n subshape, parent_ = subshape_with_parent_\n part = subshape.part\n assert part is parent_.part\n\n # fixtures ---------------------------------------------\n\n @pytest.fixture\n def subshape_with_parent_(self, request):\n parent_ = loose_mock(request, name='parent_')\n subshape = Subshape(parent_)\n return subshape, parent_\n","sub_path":"tests/shapes/test_shape.py","file_name":"test_shape.py","file_ext":"py","file_size_in_byte":12667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"618587468","text":"import scipy.integrate as sci\nimport numpy as np\n\nimport pylab\nimport matplotlib.pyplot as plt\n\n# In this file we try to solve numericaly a movement of a ball\n\n\n\n# Input parameter\n\n#----\n# Startvalue\n#----\ny0 = 0 # y-Location\nv_base = 10 # Start velocity in teta direction\nx0 = 0 # x-Location\nt_end = 1 # Duration\ntimeInc = 0.01 # Increment of time\nteta = np.array((0., 10., 30., 45., 60., 80, 90.)) # Throw angle\n\ndef rhs_y(x,t):\n ''' This function is used for solving the equation in y-direction\n\n :param x: Vector used for integration (start value ...)\n :param t: Time factor\n :return: y1_dot, y2_dot: Solution vector (integrated one)\n '''\n y1_dot = x[1]\n y2_dot = -9.81\n return [y1_dot, y2_dot]\n\ndef rhs_x(x,t):\n ''' This function is used for solving the equation in x-direction\n\n :param x: Vector used for integration (start value ...)\n :param t: Time factor\n :return: y1_dot, y2_dot: Solution vector (integrated one)\n '''\n x1_dot = x[1]\n x2_dot = 0\n return [x1_dot, x2_dot]\n\n# Time increment\nt = np.arange(0,t_end,timeInc)\n\n#-----\n## Solution of y-Values\n#----\n# Start values for the numerical method (euler right hand side)\n\nv_y0_base = v_base\nv_x0_base = v_base\nx_final = []\nfor angle in teta:\n v_y0 = v_base* np.sin(angle * np.pi / 180.)\n v_x0 = v_base * np.cos(angle * np.pi / 180.)\n # Call ode integrate\n y_0=[y0, v_y0]\n y=sci.odeint(rhs_y,y_0,t)\n #-----\n ## Solution of x-Values\n #----\n x_0=[x0, v_x0]\n x=sci.odeint(rhs_x,x_0,t)\n\n ## Plot function\n # Time plot functions\n #plt.plot(t,y)\n #plt.plot(t,x)\n # Plotting off x-y location\n x_loc = []\n for x_v_pair in x:\n x_loc.append(x_v_pair[0])\n y_loc = []\n for y_v_pair in y:\n y_loc.append(y_v_pair[0])\n # Analytical functions\n x_ana = v_x0 * t + x0\n y_ana = -0.5 * 9.81 * t**2 + t* v_y0 + y0\n x_max = v_x0 * (2*v_y0/9.81)**0.5+ x0\n # Numerical function\n plt.subplot(311)\n plt.plot(x_loc,y_loc, label=\"ana \"+str(angle) + \"; x_zero \" + str(round(x_max, 1)))\n plt.plot(x_ana,y_ana, label=\"num \"+str(angle))\n plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0.)\n plt.ylabel('y [m]')\n # Correction if the ball hits the ground\n ##plt.ylim(0,max(y_loc))\n plt.title('Throwing a ball x[m]')\n plt.grid(True)\n x_final.append(x_max)\n plt.subplot(337)\n plt.title('Rel, errror y')\n plt.plot(t, (y_loc-y_ana)/y_ana )\n plt.xlabel('t [s]')\n plt.ylabel('(y_num-y_ana)/y_ana')\n\n plt.subplot(338)\n plt.title('Rel, errror x')\n plt.plot(t, (x_loc-x_ana)/x_ana )\n plt.xlabel('t [s]')\n plt.ylabel('(x_num-x_ana)/x_ana')\n\n\n plt.subplot(334)\n plt.title('Abs, errror y')\n plt.plot(t, (y_loc-y_ana) )\n plt.ylabel('(y_num-y_ana)')\n\n plt.subplot(335)\n plt.title('Abs, errror x')\n plt.plot(t, (x_loc-x_ana))\n plt.ylabel('(x_num-x_ana)')\nplt.show()\nprint(x_final)","sub_path":"EulerWurf.py","file_name":"EulerWurf.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"546653162","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom os import path\nimport wget\n\n\nurl = \"https://www.ccontario.com/thru-the-bible\"\nreqs = requests.get(url)\nsoup = BeautifulSoup(reqs.text, \"html.parser\")\ntest_string = \"https://www.ccontario.com/\"\n# with open(\"C:\\Users\\geral\\Downloads\\Audio.txt\",\"w\") as text_file\n\nurls = []\nfor link in soup.find_all(\"a\"):\n url_text = link.get(\"href\")\n if url_text.startswith(test_string):\n x = (url_text[len(test_string) :]).strip()\n # text_file.write(x)\n print(x)\n try:\n src = f\"https://www.calvarychapelontario.com/teaching/{x}/{x}.zip\"\n save_path = f\"C:\\MotherBibleAudio\\{x}.zip\"\n if not path.exists(save_path):\n\n wget.download(src, save_path)\n print(f\"\\n---------- Completed download {x} ----------\")\n else:\n print(f\"\\n---------- {x} already exists ----------\")\n except:\n print(f\"---------- Could not download {x} ----------\")\n\n\n\"\"\"\nimport bs4\nimport requests\n\nurl = \"https://www.ccontario.com/\"\nr = requests.get(url)\ndata = bs4.BeautifulSoup(r.text, \"html.parser\")\nfor l in data.find_all(\"a\"):\n r = requests.get(url + l[\"href\"])\n print(r.status_code)\n\"\"\"\n","sub_path":"mom_bible_audio.py","file_name":"mom_bible_audio.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"241287077","text":"#-*- coding:utf-8 -*-\n__author__ = 'liubiao'\n\nfrom common.getconfig import GetConfig\nfrom common.verify import Verify\nfrom nose.plugins.attrib import attr\nfrom common.requestslib import RequestsLib\nfrom common.getexpectdata import GetExpectData\n\n@attr('hotelroute','hhub3')\nclass TestHotelRoute():\n @classmethod\n def setup_class(self):\n conf = GetConfig()\n #ged = GetExpectDate(r\".\\testproject\\hhub3\\AdminOpenTravelTransaction\\QueryToday\")\n self.verity = Verify()\n self.url = conf.get_conf_value(\"hhub3\", \"url\") + r\"api/Hotel/HotelRoute\"\n self.date = conf.get_conf_dict(\"data\")\n #self.expect_string = ged.get_json_expect_date()\n self.requestslib = RequestsLib()\n\n @classmethod\n def teardown_class(self):\n pass\n\n def test_hotel_route(self):\n u'获取酒店交通信息 '\n params = dict()\n params['HotelID'] = '2000505'\n response = self.requestslib.send_request_by_accesstoken('get',self.url,request_body=params)\n self.verity.by_status(response,200)\n\n","sub_path":"testproject/hhub3/hotel/hotelroute/testhotelroute.py","file_name":"testhotelroute.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"346015636","text":"#!/usr/bin/env python3\n\nfrom ev3dev.auto import *\n\nimport time\n\n#Let the program know that what motors are at what ports.\nmotor1 = Motor(OUTPUT_B)\nmotor2 = Motor(OUTPUT_C)\n\n#Repeat forever\nwhile (True):\n #Turn on motors. Start moving forward.\n motor1.run_forever(speed_sp = 500)\n motor2.run_forever(speed_sp = 500)\n\n #Wait 1 second\n time.sleep(1)\n\n#Move backwards\n\n","sub_path":"pynnova/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"528113895","text":"#General\ndebug = True\noutputUser = False\ndownloadWebPage = False\nsaveWebPage = False\n\n#WebInlees\n#gevondenInfo = {'team':False,'tegenstander':False,'tijd':False,'speelplaats':False}\nblokSize = 80\n\n#reistijd\nthuisAdress = 'Blauwborgje 26a, 9747 AC Groningen, Netherlands'\n\n#Rooster\nverzameltijd = 50\nwedstrijdtijd = 200\nshiftTijd = 200\nbeginTijdDag = 900\nlibo = True\nshifts = 10 if libo else 9\n\n#url is nu nog hardcoded\nurl = 'http://gchc.nl/site/default.asp?option=100&menu=1#iSjFp1MT3i5XdrVH.97' \nhorecaLeden = open('horecaLeden','r')","sub_path":"python/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"426786","text":"# -*- coding:utf-8 -*-\n#安装pymssql模块 pip install pymssql\n\nimport pymssql\n\nclass MSSQL:\n def __init__(self,host,user,pwd,db):\n self.host = host\n self.user = user\n self.pwd = pwd\n self.db = db\n\n def __GetConnect(self):\n if not self.db:\n raise(NameError,\"没有设置数据库信息\")\n self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset=\"utf8\")\n cur = self.conn.cursor()\n if not cur:\n raise(NameError,\"连接数据库失败\")\n else:\n return cur\n\n def ExecQuery(self,sql):\n cur = self.__GetConnect()\n cur.execute(sql)\n resList = cur.fetchall()\n\n #查询完毕后必须关闭连接\n self.conn.close()\n return resList\n\n def ExecNonQuery(self,sql):\n cur = self.__GetConnect()\n cur.execute(sql)\n self.conn.commit()\n self.conn.close()\n\nms = MSSQL(host=\"127.0.0.1\",user=\"sa\",pwd=\"rich123456\",db=\"HRInsurance\")\nreslist = ms.ExecQuery(\"SELECT identity_no From emp where len(identity_no)=18\")\nfor i in reslist:\n print(i)\n'''\nnewsql=\"update webuser set name='%s' where id=1\"%u'测试'\nprint(newsql)\nms.ExecNonQuery(newsql.encode('utf-8'))\n'''\n\n\n\n\n\n\n\n","sub_path":"MSSQL.py","file_name":"MSSQL.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"480862215","text":"import os\nimport sys\nfrom ctypes.util import find_library\n\nimport cffi\n\nif sys.version_info[0] == 3:\n def _reraise(ex):\n raise ex[1].with_traceback(ex[2])\nelse:\n exec('''\ndef _reraise(ex):\n raise ex[1], None, ex[2]\n ''')\n\n_pre_cache_callback_base = ['int', 'const char*', 'void*']\n_pre_callback_base = ['int', 'const char*', 'void*']\n_post_callback_base = ['int', 'int', 'const char*', 'void*']\n_callback_str = lambda c: 'int(%s)' % (', '.join(c))\n_callback_ffi = lambda c, n: 'int (*%s)(%s)' % (n, ','.join(c))\n\n__version__ = 0.2\n\nffi = cffi.FFI()\n\nffi.cdef('''\nvoid cl_init(unsigned int);\nconst char* cl_retdbdir(void);\nconst char* cl_strerror(unsigned int);\nvoid* cl_engine_new();\nint cl_load(const char*, int*, unsigned int*, unsigned int);\nint cl_engine_free(void*);\nvoid cl_engine_compile(void*);\nint cl_scanfile(const char*, const char**, unsigned long*, void*, unsigned int);\nint cl_scanfile_callback(const char*, const char**, unsigned long*, void*, unsigned int, void*);\n\nenum cl_engine_field {\n CL_ENGINE_MAX_SCANSIZE, /* uint64_t */\n CL_ENGINE_MAX_FILESIZE, /* uint64_t */\n CL_ENGINE_MAX_RECURSION, /* uint32_t */\n CL_ENGINE_MAX_FILES, /* uint32_t */\n CL_ENGINE_MIN_CC_COUNT, /* uint32_t */\n CL_ENGINE_MIN_SSN_COUNT, /* uint32_t */\n CL_ENGINE_PUA_CATEGORIES, /* (char *) */\n CL_ENGINE_DB_OPTIONS, /* uint32_t */\n CL_ENGINE_DB_VERSION, /* uint32_t */\n CL_ENGINE_DB_TIME, /* time_t */\n CL_ENGINE_AC_ONLY, /* uint32_t */\n CL_ENGINE_AC_MINDEPTH, /* uint32_t */\n CL_ENGINE_AC_MAXDEPTH, /* uint32_t */\n CL_ENGINE_TMPDIR, /* (char *) */\n CL_ENGINE_KEEPTMP, /* uint32_t */\n CL_ENGINE_BYTECODE_SECURITY, /* uint32_t */\n CL_ENGINE_BYTECODE_TIMEOUT, /* uint32_t */\n CL_ENGINE_BYTECODE_MODE, /* uint32_t */\n CL_ENGINE_MAX_EMBEDDEDPE, /* uint64_t */\n CL_ENGINE_MAX_HTMLNORMALIZE, /* uint64_t */\n CL_ENGINE_MAX_HTMLNOTAGS, /* uint64_t */\n CL_ENGINE_MAX_SCRIPTNORMALIZE, /* uint64_t */\n CL_ENGINE_MAX_ZIPTYPERCG, /* uint64_t */\n CL_ENGINE_FORCETODISK, /* uint32_t */\n CL_ENGINE_DISABLE_CACHE, /* uint32_t */\n CL_ENGINE_DISABLE_PE_STATS, /* uint32_t */\n CL_ENGINE_STATS_TIMEOUT, /* uint32_t */\n CL_ENGINE_MAX_PARTITIONS, /* uint32_t */\n CL_ENGINE_MAX_ICONSPE, /* uint32_t */\n CL_ENGINE_TIME_LIMIT /* uint32_t */\n};\n\nint cl_engine_set_num(struct cl_engine*, enum cl_engine_field, long long);\nlong long cl_engine_get_num(const struct cl_engine*, enum cl_engine_field, int*);\nint cl_engine_set_str(struct cl_engine*, enum cl_engine_field, const char*);\nconst char *cl_engine_get_str(const struct cl_engine *, enum cl_engine_field, int*);\n\ntypedef %s;\ntypedef %s;\ntypedef %s;\n\nvoid cl_engine_set_clcb_pre_cache(void*, clcb_pre_cache);\nvoid cl_engine_set_clcb_pre_scan(void*, clcb_pre_scan);\nvoid cl_engine_set_clcb_post_scan(void*, clcb_post_scan);\n''' % (_callback_ffi(_pre_cache_callback_base, 'clcb_pre_cache'),\n _callback_ffi(_pre_callback_base, 'clcb_pre_scan'),\n _callback_ffi(_post_callback_base, 'clcb_post_scan')))\n\n_bases = {'pre_cache': _pre_cache_callback_base, 'pre_scan': _pre_callback_base, 'post_scan': _post_callback_base}\n\ndbopt = {'phishing': 0x2,\n 'phishing_urls': 0x8,\n 'pua': 0x10,\n 'pua_mode': 0x80,\n 'pua_include': 0x100,\n 'pua_exclude': 0x200,\n 'official_only': 0x1000,\n 'bytecode': 0x2000,\n 'bytecode_unsigned': 0x8000,\n 'stdopt': 0x2|0x8|0x2000}\n\nscanopt = {'raw': 0x0,\n 'archive': 0x1,\n 'mail': 0x2,\n 'ole2': 0x4,\n 'blockencrypted': 0x8,\n 'html': 0x10,\n 'pe': 0x20,\n 'blockbroken': 0x40,\n 'mailurl': 0x80, #ignored\n 'blockmax': 0x100, #ignored\n 'algorithmic': 0x200,\n 'phishing_blockssl': 0x800, #ssl mismatches, not ssl by itself\n 'phishing_blockcloak': 0x1000,\n 'elf': 0x2000,\n 'pdf': 0x4000,\n 'structured': 0x8000,\n 'structured_ssn_normal': 0x10000,\n 'scructured_ssn_stripped': 0x20000,\n 'partial_message': 0x40000,\n 'heuristic_precedence': 0x80000,\n 'blockmacros': 0x100000,\n 'allmatches': 0x200000,\n 'swf': 0x400000,\n 'partition_intxn': 0x800000,\n 'file_properties': 0x10000000,\n 'performance_info': 0x40000000, #collect performance timings\n 'internal_collect_sha': 0x80000000, #Enables hash output in sha-collect builds - for internal use only\n 'stdopt': 0x1|0x2|0x4|0x4000|0x10|0x20|0x200|0x2000}\n\nresult = {'clean': 0,\n 'virus': 1,\n 'break': 22}\n\nclass ClamavError(Exception):\n def __init__(self, errcode, errstr):\n self.errcode = errcode\n super(ClamavError, self).__init__(errstr)\n\nclass engine(object):\n def __init__(self, dll_path=find_library('clamav'), init_code=0x0):\n self.exc = None\n self.libclamav = ffi.dlopen(dll_path)\n self.engine = self.libclamav.cl_engine_new()\n self.callbacks = {'pre_cache': None, 'pre_scan': None, 'post_scan': None}\n self.c_callbacks = self.callbacks\n\n def load_db(self, dbdir=None, options=dbopt['stdopt']):\n if not dbdir:\n dbdir = self.libclamav.cl_retdbdir()\n csigs = ffi.new('unsigned int*')\n ret = self.libclamav.cl_load(dbdir, self.engine, csigs, options)\n if ret != 0:\n raise ClamavError(ret, self.libclamav.strerror(ret))\n return csigs[0]\n\n def compile(self):\n # register callbacks\n for k,v in self.callbacks.items():\n if v is not None:\n getattr(self.libclamav, 'cl_engine_set_clcb_%s' % k)(self.engine, self.c_callbacks[k])\n self.libclamav.cl_engine_compile(self.engine)\n\n def scanfile(self, filename, options=scanopt['stdopt'], context=None):\n fname = ffi.new('const char[]', filename.encode())\n cvir = ffi.new('const char**')\n cscanned = ffi.new('unsigned long*')\n\n if context:\n ret = self.libclamav.cl_scanfile_callback(fname, cvir, cscanned, self.engine, options, context)\n else:\n ret = self.libclamav.cl_scanfile(fname, cvir, cscanned, self.engine, options)\n if self.exc is not None:\n _reraise(self.exc)\n if ret == result['clean']:\n return None\n elif ret == result['virus']:\n return ffi.string(cvir[0])\n else:\n raise ClamavError(ret, ffi.string(self.libclamav.cl_strerror(ret)))\n\n def _get_callback(self, n):\n return self.callbacks[n]\n\n def _set_callback(self, f, n):\n def _call(*args):\n call_args = list(args)\n for i, arg in enumerate(call_args):\n if isinstance(arg, ffi.CData) and ffi.typeof(arg) is not ffi.typeof(\"void *\"):\n try:\n call_args[i] = ffi.string(arg)\n except RuntimeError:\n call_args[i] = None\n else:\n call_args[i] = arg\n try:\n res = f(*call_args)\n if res is None:\n res = result['clean']\n if res not in result.values():\n raise ClamavError(0, '')\n except ClamavError:\n print(\"ClamavError\")\n return result['break']\n except:\n print(\"Other exception\")\n self.exc = sys.exc_info()\n return result['break']\n return res\n self.callbacks[n] = _call\n self.c_callbacks[n] = ffi.callback(_callback_str(_bases[n]), _call)\n\n @property\n def pre_cache_callback(self): return self._get_callback('pre_cache')\n\n @pre_cache_callback.setter\n def pre_cache_callback(self, f):\n self._set_callback(f, 'pre_cache')\n\n @property\n def pre_scan_callback(self): return self._get_callback('pre_scan')\n\n @pre_scan_callback.setter\n def pre_scan_callback(self, f):\n self._set_callback(f, 'pre_scan')\n\n @property\n def post_scan_callback(self): return self._get_callback('post_scan')\n\n @post_scan_callback.setter\n def post_scan_callback(self, f):\n self._set_callback(f, 'post_scan')\n\n def set_field(self, f, field, value):\n ret = f(self.engine, field, value)\n if ret != 0:\n raise ClamavError(ret, ffi.string(self.libclamav.cl_strerror(ret)))\n\n def get_field(self, f, field):\n err = 0\n err_ptr = ffi.new_handle(err)\n value = f(self.engine, field, err_ptr)\n if err != 0:\n raise ClamavError(err, ffi.string(self.libclamav.cl_strerror(err)))\n return value\n\n def set_num_field(self, field, value):\n return self.set_field(self.libclamav.cl_engine_set_num, field, value)\n\n def get_num_field(self, field):\n return self.get_field(self.libclamav.cl_engine_get_num, field)\n\n def set_str_field(self, field, value):\n return self.set_field(self.libclamav.cl_engine_set_str, field, value)\n\n def get_str_field(self, field):\n value = self.get_field(self.libclamav.cl_engine_get_str, field)\n if value == ffi.NULL:\n return \"\"\n return ffi.string(value)\n\n def __del__(self):\n if hasattr(self, 'engine'):\n self.libclamav.cl_engine_free(self.engine)\n","sub_path":"clamav.py","file_name":"clamav.py","file_ext":"py","file_size_in_byte":9611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"103805487","text":"'''\nA non validating Java parser\n\n\n\n'''\nimport pickle\nimport os\nfrom .light_parser import Lookahead, Parser, BlockStatement, Statement, Term, Seq, Optional, Node, Token # @UnresolvedImport\nfrom .lexer import JavaLexer\nfrom pygments.token import Keyword\nfrom java_parser.lexer import CommentEndOfLine\nfrom collections import defaultdict\n\ndef parse(text, discoverer=None):\n \"\"\"\n Parse a java code and return a CompilationUnit.\n \n :rtype: CompilationUnit\n \"\"\" \n parser = Parser(JavaLexer,\n [Package, Import, Parenthesis, Bracket, CurlyBracket],\n )\n \n stream = Lookahead(WhitespaceSkipper(parser.parse(text)))\n \n return JavaParser(discoverer).parse(stream)\n \n\n\nclass WhitespaceSkipper:\n \"\"\"\n Skip whitespaces.\n \"\"\"\n def __init__(self, tokens):\n self.tokens = iter(tokens)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n token = None\n while not token:\n token = next(self.tokens)\n \n if not type(token) is Token:\n break\n \n if token.is_whitespace():\n token = None\n \n return token\n \n def __repr__(self):\n return str(self.tokens)\n\n\nclass JavaParser:\n \n def __init__(self, discoverer):\n \n self.result = CompilationUnit(discoverer)\n \n def parse(self, stream):\n# print()\n modifiers = None\n elements_before = []\n new_children = []\n scope = CompilationUnit(None)\n \n try:\n while True:\n token = next(stream)\n# print(token)\n\n # store some elements still unassigned\n if token.is_comment():\n elements_before.append(token)\n elif is_modifier(token):\n modifiers = self.parse_modifiers(token, stream)\n elements_before.append(modifiers)\n \n elif isinstance(token, CurlyBracket):\n # initialiser\n if modifiers:\n \n # leave comments\n \n init = StaticInitializer(scope)\n init.children += elements_before\n elements_before = []\n init.children.append(token)\n new_children.append(init)\n else:\n # class init\n new_children.append(token)\n \n else:\n # method/constructor/variable eat till ; or {}\n local_children = []\n\n seen_assignement = False\n seen_parenthesis = False\n seen_comma = False\n length = 0\n \n while token != ';' and (not isinstance(token, CurlyBracket) or seen_assignement):\n if token == '=':\n seen_assignement = True\n \n if isinstance(token,Parenthesis) and not seen_assignement:\n seen_parenthesis = True\n self.parse_formal_parameters(token)\n length = len(local_children)\n \n local_children.append(token)\n \n if token == '=':\n token = next(stream)\n while token.is_whitespace() or token.is_comment():\n local_children.append(token)\n token = next(stream)\n local_children.append(self.parse_expression(token, stream, scope))\n \n token = next(stream)\n# print(token, scope.is_enum())\n# if scope.is_enum() and token in [',', ';', '}'] and not seen_semi_colon:\n# seen_comma = True\n# break\n \n if token == ';':\n seen_semi_colon = True\n \n if isinstance(token, CurlyBracket):\n # procedure like\n self.parse_simple_statements(token)\n \n # keep the last one\n local_children.append(token)\n \n # one can write \n # void f(...) {...};\n# print('next', stream.look_next())\n try:\n if stream.look_next() == ';':\n token = next(stream)\n local_children.append(token)\n seen_semi_colon = True\n except StopIteration:\n pass\n \n # @todo simplify\n stream.start_lookahead()\n try:\n \n look_next = next(stream)\n while look_next.is_whitespace():\n look_next = next(stream)\n \n # comment at the end of line are treated separatly\n if look_next.type == CommentEndOfLine:\n local_children += stream.stop_lookahead_and_consume()\n else:\n stream.stop_lookahead()\n except:\n stream.stop_lookahead()\n \n \n # switch on type\n element = None\n \n if seen_comma:\n element = EnumValue(scope)\n elif not seen_parenthesis:\n element = VariableDeclaration(scope) \n elif length == 1:\n # constructor\n element = Constructor(scope)\n else:\n element = Method(scope)\n \n # put what we have eaten\n element.children += elements_before\n \n element.children += local_children\n\n element.on_end()\n \n # re-init \n elements_before = []\n modifiers = None\n \n new_children.append(element)\n\n# print('next loop')\n except StopIteration:\n pass\n \n scope.elements = new_children\n return new_children\n\n def parse_annotation(self, token, stream, scope):\n \"\"\"\n Parse an annotation\n \"\"\"\n result = Annotation()\n result.children = [token]\n \n parenthesis = stream.look_next()\n \n if isinstance(parenthesis, Parenthesis):\n next(stream)\n result.children.append(parenthesis)\n self.recurse_on_annotation(parenthesis, scope)\n \n # parse annotation values\n elements = parenthesis.get_children()\n next(elements) # (\n try:\n \n first = True\n while True:\n name_or_value = next(elements)\n \n next_is_equal = False\n try:\n next_is_equal = elements.look_next() == '='\n except StopIteration:\n pass\n \n if next_is_equal:\n # named parameter\n element_name = name_or_value.text\n next(elements) # '='\n value = next(elements)\n \n result.named_parameter_expressions[element_name] = self.parse_constant(value, elements, scope)\n elif name_or_value not in [')', ',']:\n # positional parameter\n constant = self.parse_constant(name_or_value, elements, scope)\n if first:\n result.named_parameter_expressions['value'] = constant\n \n \n except StopIteration:\n pass\n \n \n \n result.on_end()\n return result\n \n def recurse_on_annotation(self, parenthesis, scope):\n \"\"\"\n Parse annotation inside annotations.\n \"\"\"\n \n stream = Lookahead(WhitespaceSkipper(parenthesis.children))\n token = next(stream)\n \n new_children = []\n \n try:\n \n while True:\n \n if is_annotation(token):\n new_children.append(self.parse_annotation(token, stream, scope))\n else:\n new_children.append(token)\n if isinstance(token, Node):\n self.recurse_on_annotation(token, scope)\n \n token = next(stream)\n \n except StopIteration:\n pass \n \n parenthesis.children = new_children\n \n \n def parse_modifiers(self, token, stream):\n \"\"\"\n Parse a modifer list\n \"\"\"\n result = Modifiers()\n result.children = [token]\n \n modifier = stream.look_next()\n \n while is_modifier(modifier):\n next(stream)\n result.children.append(modifier)\n modifier = stream.look_next()\n \n return result\n \n def parse_simple_statements(self, curly_bracket):\n \n stream = Lookahead(curly_bracket.children)\n new_children= [next(stream)] # skip {\n \n catches = []\n \n try:\n while True:\n \n token = next(stream)\n if token.text == 'catch':\n # catch (...) {...}\n catch = Catch()\n catch.children.append(token)\n catch.children.append(next(stream))\n catch.children.append(next(stream))\n \n catches.append(catch)\n elif token.text == 'finally':\n # finally {...}\n catch = Finally()\n catch.children.append(token)\n catch.children.append(next(stream))\n \n catches.append(catch)\n else:\n # something else than a catch series... \n if catches:\n c = Catches()\n c.children = catches\n \n new_children.append(c)\n else:\n new_children.append(token)\n if is_name(token):\n \n n = stream.look_next()\n if n == ';':\n # name ;\n statement = ExpressionStatement()\n statement.children.append(token)\n statement.children.append(next(stream))\n new_children.append(statement)\n elif isinstance(n, Parenthesis):\n # name (...) ;\n statement = ExpressionStatement()\n statement.children.append(token)\n statement.children.append(next(stream))\n statement.children.append(next(stream))\n new_children.append(statement)\n \n \n \n \n except StopIteration:\n pass\n \n \n curly_bracket.children = new_children\n \n def parse_expression(self, token, stream, scope):\n \"\"\"\n @todo\n \"\"\"\n if token.text and token.text[0] in ['\"', \"'\"]:\n return self.parse_simple_constant(token, scope)\n \n return token\n \n def parse_constant(self, token, stream, scope):\n \n result = self.parse_simple_constant(token, scope)\n \n token = stream.look_next()\n while token in ['+', '-', '*', '/']:\n operator = next(stream)\n token = next(stream)\n right = self.parse_simple_constant(token, scope)\n result = BinaryExpression(result, operator, right)\n token = stream.look_next()\n\n return result\n \n def parse_simple_constant(self, token, scope):\n \"\"\"\n :rtype: Expression\n \"\"\"\n if isinstance(token, CurlyBracket):\n # a set of value\n result = []\n sub_values = token.get_children()\n next(sub_values) # {\n try:\n while True:\n sub_value = next(sub_values)\n result.append(self.parse_constant(sub_value, sub_values, scope))\n next(sub_values) # ,\n except StopIteration:\n pass\n return List(result)\n elif isinstance(token, Parenthesis):\n sub_values = token.get_children()\n next(sub_values) # (\n try:\n sub_value = next(sub_values)\n return self.parse_constant(sub_value, sub_values, scope)\n except StopIteration:\n pass\n \n elif isinstance(token, Annotation):\n return token\n else:\n \n # try to convert value...\n if token.text and token.text[0] in ['\"', \"'\"]:\n return ConstantString(token.text[1:-1])\n else:\n try:\n int(token.text)\n return ConstantInteger(token)\n except:\n try:\n float(token.text)\n return ConstantInteger(token)\n except:\n pass\n # defaulting\n return Identifier(token, scope)\n\n \n \n def parse_formal_parameters(self, parenthesis):\n \n children = parenthesis.get_children()\n \n new_children = [next(children)] # openning parenthesis\n \n try:\n \n while True:\n elements = []\n token = next(children)\n \n if token == 'final':\n elements.append(token)\n token = next(children)\n \n while is_annotation(token):\n elements.append(self.parse_annotation(token, children, self.result)) # not sure here\n token = next(children)\n \n elements.append(self.parse_type(token, children))\n elements.append(next(children))\n \n parameter = FormalParameter()\n parameter.children = elements\n \n new_children.append(parameter)\n new_children.append(next(children)) # comma\n \n except StopIteration:\n pass\n \n parenthesis.children = new_children\n \n \n \n \n def parse_type(self, token, stream):\n \n result = self.parse_non_array_type(token, stream)\n \n try:\n current = stream.look_next()\n while isinstance(current, Bracket):\n current = next(stream)\n temp = ArrayType()\n temp.children.append(result)\n temp.children.append(current)\n \n result = temp\n \n current = stream.look_next()\n except StopIteration:\n pass\n \n return result\n \n \n \n def parse_generic_parameter(self, token, stream):\n \"\"\"\n token == '<'\n \"\"\"\n # ?| [extends & ...]\n # empty\n \n result = GenericParameter()\n result.children.append(token)\n \n try:\n while True:\n \n current_token = next(stream)\n if current_token == '>':\n result.children.append(current_token)\n return result\n elif current_token not in ['?', ',', '&', 'extends', 'super']:\n result.children.append(self.parse_type(current_token, stream))\n else:\n result.children.append(current_token)\n \n except StopIteration:\n pass\n \n return result\n \n def parse_non_array_type(self, token, stream):\n \"\"\"\n Type without []\n \"\"\"\n if token.text in ['void', 'byte' , 'short', 'int', 'long', 'float', 'double', 'boolean', 'char']:\n return SimpleType(token)\n\n next_token = stream.look_next()\n if next_token != '<':\n \n return SimpleType(token)\n \n \n result = GenericType()\n result.children.append(token)\n \n token = next(stream)\n result.children.append(self.parse_generic_parameter(token, stream))\n \n return result\n \n \n\n# classical opening\n\nclass Parenthesis(BlockStatement):\n\n begin = '('\n end = ')'\n \n \nclass Bracket(BlockStatement):\n\n begin = '['\n end = ']'\n \n \nclass CurlyBracket(BlockStatement):\n\n begin = '{'\n end = '}'\n\n\n\nclass Scope:\n \n def __init__(self, parent=None):\n self.parent = parent\n\n\n def resolve_qname(self, qualified_name):\n \"\"\"\n Resolve a qualified name\n \"\"\"\n names = qualified_name.split('.')\n \n current_scope = self\n \n for name in names:\n \n if isinstance(current_scope, Scope):\n current_scope = current_scope.resolve_name(name)\n if not current_scope:\n return None\n else:\n return None\n \n return current_scope\n\n def resolve_name(self, name):\n \"\"\"\n Try to resolve an unqualified name in the current scope.\n \"\"\"\n \n local = self.local_resolve_name(name)\n if local:\n return local\n \n if self.parent:\n return self.parent.resolve_name(name)\n \n \n def local_resolve_name(self, name):\n \n pass\n\n\nclass CompilationUnit(Scope):\n \"\"\"\n Root of AST.\n \"\"\"\n def __init__(self, discoverer):\n \n Scope.__init__(self)\n # a file discoverer, optional\n self.discoverer = discoverer\n self.package = None\n self.imports = []\n self.type_declaration = None\n self.elements = []\n \n self.elements_by_fullname = defaultdict(list)\n\n def get_type_declaration(self):\n \"\"\"\n Access to the class/enum/interface/... defined in this compilation unit.\n \n :rtype: Class\n \"\"\"\n return self.type_declaration\n \n def get_possible_qualified_names(self, name):\n \"\"\"\n Given a name, returns the list of possible qualified names.\n \n Using package and imports, one can determine the list of possible qualified names of a Java name.\n \n This information is generally enough for most usages.\n \n Examples :\n \n import java.util.RequestMapping;\n @RequestMapping // possible qualified names are java.util.RequestMapping\n public class MyClass {}\n \n ...\n \n package mypackage;\n @RequestMapping // possible qualified names are mypackage.RequestMapping\n public class MyClass {}\n \n ...\n \n package mypackage;\n import java.util.*;\n @RequestMapping // possible qualified names are mypackage.RequestMapping and java.util.RequestMapping\n public class MyClass {}\n \n \n \"\"\"\n # @todo can be a relative name for a an inner class...\n if '.' in name:\n return [name] # already qualified\n \n result = []\n \n for _import in self.imports:\n qname = _import.get_name().split('.')\n if len(qname) == 1:\n continue\n imported = qname[-1]\n if imported == name:\n return ['.'.join(qname)] # unique solution\n \n # import *\n if imported == '':\n qname[-1] = name\n # one of the possible solutions\n result.append('.'.join(qname))\n \n # package + name is also a solution\n if self.package:\n result.append(self.package.get_name() + '.' + name)\n else:\n result.append(name)\n \n return result\n \n def local_resolve_name(self, name):\n \n # is it the local class ?\n if self.type_declaration and name == self.type_declaration.name:\n return self.type_declaration\n \n # is it something imported ?\n# for fullname in self.get_possible_qualified_names(name):\n# \n# pathes = [path for path in self.discoverer.get_pathes(fullname) if os.path.exists(path)]\n# \n# # else ambiguous...\n# if len(pathes) == 1:\n# \n# with open_source_file(pathes[0]) as f:\n# \n# compilation_unit = parse(f.read(), self.discoverer)\n# return compilation_unit.local_resolve_name(name)\n \n \n def _calculate_elements_by_fullname(self):\n \n if not self.elements_by_fullname:\n \n for element in self.elements:\n \n if isinstance(element, VariableDeclaration):\n self.elements_by_fullname[element.name.text].append(element)\n \n def get_element(self, fullname):\n \"\"\"\n Search a class, method, field etc... by its fullname\n \"\"\"\n self._calculate_elements_by_fullname()\n \n try:\n return self.elements_by_fullname[fullname]\n except:\n pass\n \n def save(self, path):\n \"\"\"\n Passivation to disk\n \"\"\"\n with open(path, \"wb\") as f:\n pickle.dump(self, f, pickle.HIGHEST_PROTOCOL)\n \n \n @staticmethod\n def load(path):\n \"\"\"\n Depassivation from disk\n \"\"\"\n with open(path, \"rb\") as f:\n return pickle.load(f)\n \n \n\nclass Package(Statement):\n\n begin = 'package'\n end = ';'\n \n def __init__(self):\n Statement.__init__(self)\n self.name = None\n \n def get_name(self):\n \"\"\"\n Get package name.\n \n :rtype: str\n \"\"\"\n return self.name.text;\n \n def on_end(self):\n\n tokens = self.get_children()\n next(tokens)\n token = next(tokens)\n self.name = token\n \n\nclass Import(Statement):\n\n begin = 'import'\n end = ';'\n\n def get_name(self):\n \"\"\"\n Get imported name.\n\n :rtype: str\n \"\"\"\n return self.name.text;\n \n def on_end(self):\n\n tokens = self.get_children()\n next(tokens)\n token = next(tokens)\n self.name = token\n\ndef is_annotation(token):\n \n return token.text and token.text[0] == '@' and not token.text == '@interface'\n\ndef is_modifier(token):\n \n return token.text in ['public', 'private', 'protected', \n 'abtsract', 'static', 'final', 'strictfp',\n 'native', 'synchronized', 'transient']\n\ndef is_class(token):\n \n return token.text in ['class', 'interface', 'enum', '@interface'] \n\n\ndef parse_constant(value):\n \"\"\"\n value is a constant element\n \n :rtype: python type with correct elements (for example list of string/int, ...)\n \"\"\"\n if isinstance(value, CurlyBracket):\n # a set of value\n result = []\n sub_values = value.get_children()\n next(sub_values) # {\n try:\n while True:\n \n sub_value = next(sub_values)\n result.append(parse_constant(sub_value))\n next(sub_values) # ,\n except StopIteration:\n pass\n \n return result\n elif isinstance(value, Annotation):\n return value\n else:\n \n # try to convert value...\n if value.text and value.text[0] in ['\"', \"'\"]:\n return value.text[1:-1]\n else:\n try:\n return int(value.text)\n except:\n try:\n return float(value.text)\n except:\n pass\n return value.text\n\n\nclass Annotation(Term):\n \"\"\"\n An annotation\n \"\"\"\n\n def __init__(self):\n Term.__init__(self)\n self.name = None\n self.named_parameters = {}\n self.named_parameter_expressions = {}\n self.named_parameters_calculated = False\n \n def get_type_name(self):\n \"\"\"\n Get the name of the annotation class.\n\n :rtype: str\n \"\"\"\n return self.name\n \n def get_named_parameters(self):\n \"\"\"\n Get the annotation named parameters.\n \n :rtype: map str -> something (int, str)\n \"\"\"\n if not self.named_parameters_calculated:\n \n self.named_parameters = {}\n for key in self.named_parameter_expressions:\n \n self.named_parameters[key] = self.named_parameter_expressions[key].evaluate_as_constant()\n \n self.named_parameters_calculated = True\n \n return self.named_parameters\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return self\n\n def to_text(self):\n return str(self)\n\n def on_end(self):\n\n tokens = self.get_children()\n name = next(tokens)\n self.name = name.text[1:]\n \n try:\n parenthesis = next(tokens)\n elements = parenthesis.get_children()\n next(elements) # (\n try:\n \n first = True\n while True:\n name_or_value = next(elements)\n \n next_is_equal = False\n try:\n next_is_equal = elements.look_next() == '='\n except StopIteration:\n pass\n \n if next_is_equal:\n # named parameter\n element_name = name_or_value.text\n next(elements) # '='\n value = next(elements)\n \n self.named_parameters[element_name] = parse_constant(value)\n elif name_or_value not in [')', ',']:\n # positional parameter\n constant = parse_constant(name_or_value)\n if first:\n self.named_parameters['value'] = constant\n \n \n except StopIteration:\n pass\n \n \n except StopIteration:\n pass\n \n\ndef match_annotation_list(_token, stream):\n \n token = _token\n \n index_of_stream = stream.tokens.index\n \n seen = False\n # accepts list of annotations\n while isinstance(token, Annotation):\n # this index is correct\n index_of_stream = stream.tokens.index\n token = next(stream)\n seen = True\n \n # whatever reason we reput as the last one correct\n stream.tokens.index = index_of_stream\n \n return seen\n\n\ndef match_modifier_list(_token, stream):\n\n token = _token\n\n index_of_stream = stream.tokens.index\n \n seen = False\n \n # then things like public, etc...\n while token.text in ['public', 'private', 'protected', \n 'abtsract', 'static', 'final', 'strictfp',\n 'native', 'synchronized', 'transient']:\n # this index is correct\n index_of_stream = stream.tokens.index\n token = next(stream)\n seen = True\n \n # whatever reason we reput as the last one correct\n stream.tokens.index = index_of_stream\n \n return seen\n\n\n\n\nclass Modifiers(Term):\n \n match = match_modifier_list\n\n\ndef is_name(token):\n \n return not is_keyword(token) and token.text and token.text[0].isalpha()\n\n\nclass JavaStructureElement:\n \n def get_header_comments(self):\n \n tokens = iter(self.children)\n \n result = []\n token = None\n try:\n while token not in ['class', 'interface', 'enum', '@interface']:\n token = next(tokens)\n if token.is_comment():\n result.append(token)\n except StopIteration:\n pass\n \n return result\n\n\nclass Class(JavaStructureElement, BlockStatement, Scope):\n \"\"\"\n Class, interface, enum, annotation.\n \n [AnnotationList] [Modifiers] class|interface|enum|@intereface ... CurlyBracket\n \"\"\"\n \n def __init__(self, parent):\n BlockStatement.__init__(self)\n Scope.__init__(self, parent)\n self.name = None\n self.annotations = []\n self.modifiers = []\n self.extends = []\n\n def get_name(self):\n \"\"\"\n Access to class name\n\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \n :rtype: list of Annotation\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def get_extends(self):\n \"\"\"\n Inherited class or None\n \n @todo implement\n :rtype: Class or NoneType\n \"\"\"\n return self.extends\n \n def get_methods(self):\n \"\"\"\n Access to class methods\n\n :rtype: list of Method\n \"\"\"\n # not in on_end, because would not work\n for block in self.get_sub_nodes(CurlyBracket):\n \n return list(block.get_sub_nodes(Method))\n \n def get_constructors(self):\n \"\"\"\n Access to class constructors\n \n :rtype: list of Constructor\n \"\"\"\n # not in on_end, because would not work\n for block in self.get_sub_nodes(CurlyBracket):\n \n return list(block.get_sub_nodes(Constructor))\n\n def get_fields(self):\n \"\"\"\n Access to class fields\n\n :rtype: list of VariableDeclaration\n \"\"\"\n # not in on_end, because would not work\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(VariableDeclaration))\n\n def get_enum_values(self):\n \"\"\"\n In case of enum access to constants.\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(EnumValue))\n\n def get_instance_initializers(self):\n \"\"\"\n :rtype: list of CurlyBracket\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(CurlyBracket))\n\n def get_static_initializers(self):\n \"\"\"\n :rtype: list of StaticInitializer\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(StaticInitializer))\n \n def get_type_declarations(self):\n \"\"\"\n Inner class declarations.\n \n :rtype: list of Class\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n return list(block.get_sub_nodes(Class))\n \n def is_enum(self):\n \"\"\"\n True if class is an enum\n \"\"\"\n tokens = self.get_children()\n kind = tokens.move_to(['class', 'interface', 'enum', '@interface'])\n return kind == 'enum'\n \n def local_resolve_name(self, name):\n \n for child in self.get_methods():\n if child.name == name:\n return child\n \n for child in self.get_constructors():\n if child.name == name:\n return child\n\n for child in self.get_fields():\n if child.name == name:\n return child\n\n for child in self.get_type_declarations():\n if child.name == name:\n return child\n \n pass\n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n \n for modifiers in self.get_sub_nodes(Modifiers):\n self.modifiers = list(modifiers.get_children())\n\n tokens = self.get_children()\n tokens.move_to(['class', 'interface', 'enum', '@interface'])\n \n \n self.name = next(tokens)\ndef is_keyword(token):\n \n return token.type == Keyword\n\n\ndef is_type(token, stream):\n \n if not is_non_array_type(token, stream):\n return False\n \n index_of_stream = stream.tokens.index\n \n try:\n token = next(stream)\n \n while isinstance(token,Bracket):\n index_of_stream = stream.tokens.index\n token = next(stream)\n \n except StopIteration:\n pass\n stream.tokens.index = index_of_stream\n return True\n\ndef is_generic_type_parameter(token, stream):\n \n # ?| [extends & ...]\n# print(\"is_generic_type_parameter\", stream.tokens.index, stream.tokens)\n \n if token != '?' and not is_type(token, stream):\n return False\n \n index_of_stream = stream.tokens.index\n token = next(stream)\n if token.text != 'extends':\n stream.tokens.index = index_of_stream\n return True\n \n token = next(stream)\n if not is_type(token, stream):\n stream.tokens.index = index_of_stream\n return False\n \n index_of_stream = stream.tokens.index\n token = next(stream)\n while token == '&':\n token = next(stream)\n is_type(token, stream)\n \n index_of_stream = stream.tokens.index\n token = next(stream)\n\n stream.tokens.index = index_of_stream\n return True\n \ndef is_non_array_type(token, stream):\n \"\"\"\n Type without []\n \"\"\"\n if token.text in ['void', 'byte' , 'short', 'int', 'long', 'float', 'double', 'boolean', 'char']:\n return True\n \n if not is_name(token):\n return False\n \n # for rollbacking\n index_of_stream = stream.tokens.index\n \n try:\n token = next(stream)\n if token != '<':\n stream.tokens.index = index_of_stream\n return True\n \n # here we have matched \n # name < \n \n \n index_of_stream = stream.tokens.index\n token = next(stream)\n while is_generic_type_parameter(token, stream):\n token = next(stream)\n if token == '>':\n break\n if token == ',':\n token = next(stream)\n else:\n # something bad happenned\n stream.tokens.index = index_of_stream\n return False\n\n except StopIteration:\n pass\n \n # and again with commas till > \n return True\n \n\ndef is_throws(token, stream):\n \n if token.text != 'throws':\n return False\n \n # eats type, type, ...\n # fragile...\n token = next(stream)\n while is_type(token, stream):\n index_of_stream = stream.tokens.index\n \n token = next(stream)\n if token != ',':\n stream.tokens.index = index_of_stream\n return True\n else:\n token = next(stream)\n \n\nclass Throws(Term):\n \n match = is_throws\n\n\nclass MethodLike(Scope):\n \n def __init__(self, parent):\n Scope.__init__(self, parent)\n self.__parsed = False\n \n def get_statements(self):\n \"\"\"\n Access to method statements\n \"\"\"\n for block in self.get_sub_nodes(CurlyBracket):\n \n # on demand statement parsing\n if not self.__parsed:\n parser = Parser(JavaLexer,\n [Assert, Break, Continue, Return, Throw, Switch, DoWhile, Try],\n )\n \n # need one loop to force the parsing\n for _ in recursive_statement_pass(parser.parse_stream([block])):\n pass\n \n self.__parsed = True\n \n return list(block.get_sub_nodes(JavaStatement))\n \n def get_parameters(self):\n \"\"\"\n Access to method parameters\n \n :rtype: list FormalParameter\n \"\"\"\n for parenthesis in self.get_sub_nodes(Parenthesis):\n \n return list(parenthesis.get_sub_nodes(FormalParameter))\n \n\nclass EnumValue(JavaStructureElement, Term):\n \n def __init__(self, parent):\n Term.__init__(self)\n self.name = None\n self.annotations = []\n \n def get_name(self):\n \"\"\"\n Access to name.\n\n :rtype: str\n \"\"\"\n return self.name.text\n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n\n tokens = self.get_children()\n token = next(tokens)\n\n while isinstance(token, Annotation):\n token = next(tokens)\n \n # here we assume that name is a single token\n self.name = token\n \n\nclass Method(JavaStructureElement, Term, MethodLike):\n \"\"\"\n [AnnotationList] [Modifiers] [AnnotationList] Parenthesis [throws , ...] CurlyBracket|;\n \"\"\"\n \n def __init__(self, parent):\n Term.__init__(self)\n MethodLike.__init__(self, parent)\n \n self.name = None\n self.annotations = []\n self.modifiers = []\n self.type = []\n \n def get_name(self):\n \"\"\"\n Access to name.\n\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n\n tokens = self.get_children()\n token = next(tokens)\n \n while isinstance(token, Annotation):\n token = next(tokens)\n \n if isinstance(token, Modifiers):\n self.modifiers += list(token.get_children())\n token = next(tokens)\n \n # here we are on type...\n while not isinstance(token, Parenthesis):\n self.type.append(token)\n token = next(tokens)\n \n # here we assume that name is a single token\n self.name = self.type[-1]\n self.type = self.type[:-1]\n \n # here token is parenthesis and contains parameters... \n\n\nclass Constructor(JavaStructureElement, Term, MethodLike):\n \"\"\"\n [AnnotationList] [Modifiers] Parenthesis [throws , ...] CurlyBracket\n \"\"\"\n \n def __init__(self, parent):\n Term.__init__(self)\n MethodLike.__init__(self, parent)\n \n self.name = None\n self.annotations = []\n self.modifiers = []\n \n def get_name(self):\n \"\"\"\n Access to name.\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def on_end(self):\n \n tokens = self.get_children()\n token = next(tokens)\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n \n while isinstance(token, Annotation):\n token = next(tokens)\n \n if isinstance(token, Modifiers):\n self.modifiers += list(token.get_children())\n token = next(tokens)\n \n self.name = token\n \n # here token is parenthesis and contains parameters... \n\n\nclass StaticInitializer(Term, MethodLike):\n \n match = Seq('static', CurlyBracket)\n\n def __init__(self, parent):\n Term.__init__(self)\n MethodLike.__init__(self, parent)\n\n\nclass VariableDeclaration(JavaStructureElement, Statement, Scope):\n \"\"\"\n Member variable also...\n \n [AnnotationList] [Modifiers] [= ...] ;\n \"\"\"\n\n def __init__(self, parent):\n Statement.__init__(self)\n Scope.__init__(self, parent)\n self.name = None\n self.annotations = []\n self.modifiers = []\n self.type = []\n self.initialisation = None\n \n def get_name(self):\n \"\"\"\n Access to name.\n :rtype: str\n \"\"\"\n return self.name.text\n \n def get_annotations(self):\n \"\"\"\n Access to class annotations\n \"\"\"\n return self.annotations\n \n def get_modifiers(self):\n \"\"\"\n Access to class modifiers\n \"\"\"\n return self.modifiers\n \n def get_initialisation(self):\n \"\"\"\n :rtype: Expression\n \"\"\"\n return self.initialisation\n \n \n def on_end(self):\n \n self.annotations = list(self.get_sub_nodes(Annotation))\n\n tokens = self.get_children()\n token = next(tokens)\n\n while isinstance(token, Annotation):\n token = next(tokens)\n\n if isinstance(token, Modifiers):\n self.modifiers += list(token.get_children())\n token = next(tokens)\n \n # here we are on type...\n while not token in ['=', ';']:\n self.type.append(token)\n token = next(tokens)\n \n # here we assume that name is a single token\n self.name = self.type[-1]\n self.type = self.type[:-1]\n \n if token != '=':\n return\n \n self.initialisation = next(tokens)\n \n\n### For statements\n\"\"\"\n\n\nTodo:\n\n synchronized ParExpression Block\n\n\nHope useless ??:\n Identifier : Statement\n ;\n\nPartially :\n## StatementExpression ;\n\n method ... ;\n\nDone:\n** Block\n** do Statement while ParExpression ;\n** assert Expression [: Expression] ;\n** switch ParExpression { SwitchBlockStatementGroups } \n** break [Identifier] ;\n** continue [Identifier] ;\n** return [Expression] ;\n** throw Expression ;\n** if ParExpression Statement [else Statement] \n** for ( ForControl ) Statement\n** while ParExpression Statement\n** try Block (Catches | [Catches] Finally)\n** try ResourceSpecification Block [Catches] [Finally]\n\n\"\"\"\n\"\"\"\nExpressions:\n\nTodo:\n new ;\n \n \n \n \n\"\"\"\n\n\nclass JavaStatement():\n pass\n\n\nclass JavaSimpleStatement(JavaStatement, Statement):\n pass\n\n\nclass JavaBlockStatement(JavaStatement, BlockStatement):\n pass\n\n\nclass Assert(JavaSimpleStatement):\n\n begin = 'assert'\n end = ';'\n\n\nclass Break(JavaSimpleStatement):\n\n begin = 'break'\n end = ';'\n\n\nclass Continue(JavaSimpleStatement):\n\n begin = 'continue'\n end = ';'\n\n\nclass Return(JavaSimpleStatement):\n\n begin = 'return'\n end = ';'\n\n\nclass Throw(JavaSimpleStatement):\n\n begin = 'throw'\n end = ';'\n\n\nclass Catch(Term):\n \n match = Seq('catch', Parenthesis, CurlyBracket)\n\n\n\ndef is_catches(token, stream):\n \"\"\"\n catches ... and finally\n \"\"\"\n if isinstance(token, Finally):\n return False\n \n if not isinstance(token, Catch):\n return False\n \n # eats Catch Catch\n index_of_stream = stream.tokens.index\n\n try:\n token = next(stream)\n\n while isinstance(token, Catch) or isinstance(token, Finally):\n index_of_stream = stream.tokens.index\n token = next(stream)\n \n except:\n pass\n \n stream.tokens.index = index_of_stream\n return True\n \n\nclass Catches(Term):\n \n match = is_catches\n\n\nclass Finally(Term):\n\n match = Seq('finally', CurlyBracket)\n\n\nclass Try(JavaStatement, Term):\n \n match = Seq('try', Optional(Parenthesis), CurlyBracket, Optional(Catches))\n \n def get_catches(self):\n \"\"\"\n Access to catches blocks\n \"\"\"\n for node in self.get_sub_nodes(Catches):\n return node.get_sub_nodes(Catch)\n\n \n def get_finally(self):\n \"\"\"\n Access to finally block if exist\n \"\"\"\n for node in self.get_sub_nodes(Catches):\n for f in node.get_sub_nodes(Finally):\n return f\n \n \n\nclass Switch(JavaSimpleStatement):\n\n begin = 'switch'\n end = CurlyBracket\n\n\nclass ExpressionStatement(JavaStatement, Term):\n\n match = Seq(is_name, Optional(Parenthesis), ';')\n\n\nclass DoWhile(JavaBlockStatement):\n \n begin = 'do' \n end = Seq('while', Parenthesis, ';')\n\n def get_statemens(self):\n # @todo\n pass\n \n\nclass If(JavaBlockStatement):\n \n \n def get_condition(self):\n \"\"\"\n The condition of the if\n \"\"\"\n return list(self.get_sub_nodes())[0]\n \n def get_then(self):\n \"\"\"\n The then part\n \"\"\"\n return list(self.get_sub_nodes())[1]\n \n def get_else(self):\n \"\"\"\n The else part\n \"\"\"\n try:\n return list(self.get_sub_nodes())[2]\n except:\n pass\n\n\nclass For(JavaBlockStatement):\n\n def get_for_control(self):\n \"\"\"\n The control of the for\n \n for (....)\n ------\n \"\"\"\n return list(self.get_sub_nodes())[0]\n \n def get_statement(self):\n \"\"\"\n Access to the statement looped.\n \"\"\"\n return list(self.get_sub_nodes())[1]\n \n\n\nclass While(JavaBlockStatement):\n\n def get_condition(self):\n \"\"\"\n The condition of the while\n \"\"\"\n return list(self.get_sub_nodes())[0]\n\n def get_statement(self):\n \"\"\"\n Access to the statement looped.\n \"\"\"\n return list(self.get_sub_nodes())[1]\n\n \ndef recursive_statement_pass(stream):\n \"\"\"\n Special treatment for if/for/while\n \"\"\"\n \n for node in stream:\n handle_node(node)\n yield node\n\n\ndef handle_node(node):\n \n # recurse\n if isinstance(node, Node):\n for sub in node.get_sub_nodes():\n handle_node(sub)\n \n if isinstance(node, CurlyBracket):\n handle_block(node)\n \n\ndef handle_block(node):\n \"\"\"\n Here we get the CurlyBracket nodes\n \"\"\"\n# print('handling block...')\n \n # re-manipulate node.children to create sub nodes for if/else, for () statement, while () statement,\n stream = SimpleStream(node.children)\n\n new_children = []\n \n try:\n while True:\n new_children.append(consume(stream))\n \n except StopIteration:\n pass\n \n \n node.children = new_children\n \n# print()\n# for child in new_children:\n# print(' ', child)\n\n\nclass SimpleStream:\n \n def __init__(self, elements):\n \n self.elements = elements\n self.index = 0\n \n def __iter__(self):\n return self\n\n def __next__(self):\n \n try:\n index = self.index\n self.index += 1\n return self.elements[index]\n except:\n raise StopIteration\n \n def look_next(self):\n \n return self.look(1)\n \n def look(self, delta):\n \"\"\"\n Look future...\n \"\"\"\n try:\n return self.elements[self.index+delta]\n except:\n return None\n \n def peek_next(self):\n \"\"\"\n Look for the next significative token\n \"\"\"\n delta = 1\n peek = None\n while True:\n \n peek = self.look(delta)\n delta += 1\n \n if not peek:\n break\n if not (peek.is_whitespace() or peek.is_comment()):\n break\n \n return peek\n \n\n\ndef eat_statement(stream, l):\n\n # eat up to a node\n # recursive, but will not work for 1; ...\n while True: \n then = consume(stream)\n l.append(then)\n if isinstance(then, Node):\n break\n\n\n\ndef consume(stream):\n \"\"\"\n Main parsing for if, for, while\n \"\"\"\n token = next(stream)\n if token.text == 'if':\n \n result = If()\n result.children.append(token)\n \n # eat up to parenthesis\n while True: \n token = next(stream)\n result.children.append(token)\n if isinstance(token, Parenthesis):\n break\n \n# print(result.children)\n eat_statement(stream, result.children)\n# print(result.children)\n\n # have we a else ?\n peek = stream.peek_next()\n# print(peek)\n if peek.text == 'else':\n \n # eat up to else\n while True:\n token = next(stream)\n result.children.append(token)\n if token.text == 'else':\n break\n \n # eat the next statement\n eat_statement(stream, result.children)\n \n return result\n \n elif token.text == 'for':\n \n result = For()\n result.children.append(token)\n \n # eat up to parenthesis\n while True: \n token = next(stream)\n result.children.append(token)\n if isinstance(token, Parenthesis):\n break\n \n eat_statement(stream, result.children)\n \n return result\n\n elif token.text == 'while':\n \n result = While()\n result.children.append(token)\n \n # eat up to parenthesis\n while True: \n token = next(stream)\n result.children.append(token)\n if isinstance(token, Parenthesis):\n break\n \n eat_statement(stream, result.children)\n \n return result\n \n return token \n\n\n# ???\n \nclass Expression:\n pass\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return \"\"\n\n\nclass BinaryExpression(Expression):\n\n def __init__(self, left, operator, right):\n Expression.__init__(self)\n self.left = left\n self.operator = operator\n self.right = right\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n \n # only + for the moment\n if self.operator == '+':\n \n left = self.left.evaluate_as_constant()\n right = self.right.evaluate_as_constant()\n \n return left + right\n else:\n return self.left.to_text() + self.operator.text + self.right.to_text()\n \n def to_text(self):\n return \"\"\n\n def __repr__(self):\n \n return \"%s %s %s\" % (self.left, self.operator.text, self.right)\n\n\nclass ConstantString(Expression):\n def __init__(self, token):\n self.value = token\n \n def __repr__(self):\n return \"Constant(\\\"%s\\\")\" % self.value\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return self.value\n \n def to_text(self):\n return self.value.text\n\n\nclass ConstantInteger(Expression):\n def __init__(self, token):\n self.value = token\n\n def __repr__(self):\n return \"Constant(%s)\" % self.value\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return int(self.value.text)\n\n def to_text(self):\n return str(self.value)\n \n\nclass ConstantFloat(Expression):\n def __init__(self, token):\n self.value = token\n\n def __repr__(self):\n return \"Constant(%s)\" % self.value\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return float(self.value)\n\n def to_text(self):\n return str(self.value)\n\n\nclass Identifier(Expression):\n def __init__(self, token, scope=None):\n self.identifier = token\n # we need a scope to resolve its value latter\n self.scope = scope\n\n def __repr__(self):\n return self.identifier.text\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n try:\n if self.scope:\n # we can try to resolve it\n resolved_as = self.scope.resolve_qname(self.identifier.text)\n if resolved_as and isinstance(resolved_as, VariableDeclaration):\n \n init_expression = resolved_as.get_initialisation()\n if init_expression:\n \n return init_expression.evaluate_as_constant()\n except:\n pass # shit may happen\n \n return self.identifier.text\n\n def to_text(self):\n return self.identifier.text\n\n\nclass List(Expression):\n def __init__(self, elements):\n self.elements = elements\n\n def __repr__(self):\n return \"List(%s)\" % self.elements\n\n def evaluate_as_constant(self):\n \"\"\"\n Evaluate an expression as a constant.\n \"\"\"\n return [element.evaluate_as_constant() for element in self.elements]\n\n def to_text(self):\n return \"{\" + ','.join([element.to_text() for element in self.elements]) + \"}\"\n\n\n\ndef get_all_tokens(node):\n \n result = []\n \n for t in node.children:\n if isinstance(t, Node):\n result += get_all_tokens(t)\n else:\n result.append(t)\n \n return result\n\n\nclass Type:\n \n \n def __repr__(self): \n return ''.join(token.text for token in get_all_tokens(self))\n\n \n \n\nclass SimpleType(Type, Node):\n \"\"\"\n predefined type of class\n \"\"\"\n def __init__(self, token):\n Node.__init__(self)\n self.children = [token]\n\n def get_type_name(self):\n \"\"\"\n Get the name of the type.\n :rtype: str\n \"\"\"\n return self.children[0].text\n \n\nclass ArrayType(Type, Node):\n \"\"\"\n ... []\n \"\"\"\n \n def get_type(self):\n \"\"\"\n Access to type on which we do an array\n \"\"\"\n return next(self.get_sub_nodes())\n \n\nclass GenericType(Type, Node):\n \"\"\"\n @todo : maybe we need a SimpleType here as first child ?\n ... < ... >\n \"\"\"\n pass\n\n\nclass GenericParameter(Node):\n pass\n \n\nclass FormalParameter(Node):\n \"\"\"\n A formal parameter of a method.\n \"\"\"\n \n def get_name(self):\n \"\"\"\n Parameter name\n \n :rtype: str\n \"\"\"\n for child in self.get_children():\n if child == 'final':\n continue\n \n if isinstance(child, Annotation):\n continue\n \n if isinstance(child, Type):\n continue\n \n return child.text\n\n def get_type(self):\n \"\"\"\n Parameter type\n \n :rtype: Type\n \"\"\"\n for child in self.get_children():\n\n if isinstance(child, Type):\n \n return child\n\n\ndef open_source_file(path):\n \"\"\"\n Equivalent of python open(path) that autotdetects encoding. \n \n :rtype: file \n \"\"\"\n from chardet.universaldetector import UniversalDetector\n \n detector = UniversalDetector()\n with open(path, 'rb') as f:\n count = 0\n for line in f:\n detector.feed(line)\n count += 1\n if detector.done or count > 100: \n break\n detector.close()\n\n encoding = detector.result['encoding']\n \n result = open(path, 'r', encoding=encoding, errors='replace')\n return result\n","sub_path":"analyze/extensions/com.castsoftware.html5.2.0.8-funcrel/java_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":56975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"178382087","text":"# -*- encoding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals, division\nimport logging\n\nimport threading\ntry:\n import queue\nexcept ImportError:\n import Queue as queue\nfrom enocean.protocol.packet import Packet\nfrom enocean.protocol.constants import PARSE_RESULT\n\nlogger = logging.getLogger('enocean.communicators.Communicator')\n\n\nclass Communicator(threading.Thread):\n '''\n Communicator base-class for EnOcean.\n Not to be used directly, only serves as base class for SerialCommunicator etc.\n '''\n def __init__(self, callback=None):\n super(Communicator, self).__init__()\n # Create an event to stop the thread\n self._stop_flag = threading.Event()\n # Input buffer\n self._buffer = []\n # Setup packet queues\n self.transmit = queue.Queue()\n self.receive = queue.Queue()\n # Set the callback method\n self.__callback = callback\n \n def _get_from_send_queue(self):\n ''' Get message from send queue, if one exists '''\n try:\n p = self.transmit.get(block=False)\n logger.info('Sending packet')\n logger.debug(p)\n return p\n except queue.Empty:\n pass\n return None\n\n def send(self, packet):\n if not isinstance(packet, Packet):\n logger.error('Object to send must be an instance of Packet')\n return False\n self.transmit.put(packet)\n return True\n\n def stop(self):\n self._stop_flag.set()\n\n def parse(self):\n ''' Parses messages and puts them to receive queue '''\n # Loop while we get new messages\n while True:\n status, self._buffer, p = Packet.parse_msg(self._buffer)\n # If message is incomplete -> break the loop\n if status == PARSE_RESULT.INCOMPLETE:\n return status\n\n # If message is OK, add it to receive queue or send to the callback method\n if status == PARSE_RESULT.OK and p:\n if self.__callback is None:\n self.receive.put(p)\n else:\n self.__callback(p)\n logger.debug(p)\n","sub_path":"enocean/communicators/communicator.py","file_name":"communicator.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"651616629","text":"#!/usr/bin/env python\n\nfrom itertools import izip\nfrom os import chdir\nfrom pathlib import Path\nfrom subprocess import check_call\n\ndef main():\n base = Path(__file__).parent.parent.parent\n chdir(str(base))\n clean = Path().glob(r'[c-f]_*/aa*.py')\n for y in clean:\n y.unlink()\n subdirs = Path().glob(r'[b-f]_*')\n d0 = next(subdirs)\n template = tuple(_list_paths(d0))\n contents = tuple(_content(path) for path in template)\n template = (path.name for path in template)\n replace = tuple(path.replace(str(d0)[0], r'{}') for path in template)\n name_template = str(d0)\n for subdir in subdirs:\n name = str(subdir)\n n0 = name[0]\n for r, c in izip(replace, contents):\n c = c.replace(name_template, name)\n output = subdir.joinpath(r.format(n0))\n with output.open('wb') as ostream:\n ostream.write(c)\n check_call(r'git add {}'.format(str(output)), shell=True)\n\ndef _content(path):\n with path.open('rb') as istream:\n return istream.read()\n\ndef _list_paths(y):\n c = str(y)[0]\n pat = r'aa_{}[01]*.py'.format(c)\n for path in y.glob(pat):\n yield path\n\nif __name__ == r'__main__':\n main()\n","sub_path":"zz/aa20141119.py","file_name":"aa20141119.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"653572360","text":"# coding: utf-8\nimport datetime\nimport json\nimport time\nimport urllib\n\n#import brukva\n#import aioredis\nimport tornadoredis\n#from aredis import StrictRedis\nimport tornado.web\nimport tornado.websocket\nimport tornado.ioloop\nimport tornado.httpclient\nfrom django.shortcuts import render, get_object_or_404\nfrom privatemessages.models import Read\n\n\nfrom django.conf import settings\nfrom importlib import import_module\n\nsession_engine = import_module(settings.SESSION_ENGINE)\n\nfrom django.contrib.auth.models import User\n\nc = tornadoredis.Client()\nc.connect()\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.set_header('Content-Type', 'text/plain')\n self.write('Hello. :)')\n\nclass MessagesHandler(tornado.websocket.WebSocketHandler):\n\n waiters = set()\n\n def __init__(self, *args, **kwargs):\n super(MessagesHandler, self).__init__(*args, **kwargs)\n self.client = tornadoredis.Client()\n self.client.connect()\n\n def check_origin(self, origin):\n return True\n\n def open(self, user_id):\n session_key = self.get_cookie(settings.SESSION_COOKIE_NAME)\n session = session_engine.SessionStore(session_key)\n try:\n self.user_id = session[\"_auth_user_id\"]\n self.sender_name = User.objects.get(id=self.user_id).username\n except (KeyError, User.DoesNotExist):\n self.close()\n return\n self.channel = user_id\n self.waiters.add((self))\n print(self.channel)\n print('выполнн')\n self.client.listen(self.show_new_message)\n\n def handle_request(self, response):\n pass\n\n def show_new_message(self, result):#python manage.py starttornadooffers\n print('ЗАЯВКА!')\n self.write_message(str(result.body))\n\n def on_message(self, message):\n print(\"message\")\n for waiter in self.waiters:\n if waiter.channel == self.channel:\n waiter.write_message(message)\n print(\"message_send\")\n\n def on_close(self):\n print('close!')\n try:\n self.waiters.remove((self))\n #self.client.unsubscribe(self.channel)\n except AttributeError:\n pass\n def check():\n if self.client.connection.in_progress:\n tornado.ioloop.IOLoop.instance().add_timeout(\n datetime.timedelta(0.00001),\n check\n )\n else:\n self.client.disconnect()\n tornado.ioloop.IOLoop.instance().add_timeout(\n datetime.timedelta(0.00001),\n check\n )\n\napplication = tornado.web.Application([\n (r\"/\", MainHandler),\n (r'/(?P\\d+)/', MessagesHandler),\n])","sub_path":"nicechange/offers/tornadooffers.py","file_name":"tornadooffers.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"122362640","text":"from flask import Flask, render_template, request\n\nfrom urllib.parse import quote\n\nfrom weather_retriever import get_weather\nfrom forex_retriever import get_rate, get_all_currencies\nfrom news_retriever import get_news\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n source = request.args.get('source')\n source = 'bbc' if not source else source.lower()\n articles = get_news(source)\n\n query = request.args.get('location')\n query = 'London, UK' if not query else query\n weather = get_weather(quote(query))\n\n all_currencies = get_all_currencies()\n\n src_currency = request.args.get('src_currency')\n src_currency = 'GBP' if not src_currency else src_currency\n dst_currency = request.args.get('dst_currency')\n dst_currency = 'VND' if not dst_currency else dst_currency\n rate = get_rate(src_currency, dst_currency)\n forex = {\n 'src_currency': src_currency,\n 'dst_currency': dst_currency,\n 'rate': rate\n }\n\n return render_template('index.html', articles=articles, weather=weather, currencies=all_currencies, forex=forex)\n\nif __name__ == '__main__':\n app.run(port=8888, debug=True)\n","sub_path":"headlines.py","file_name":"headlines.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"564208380","text":"from flask import Flask, render_template, request\nfrom sklearn.externals import joblib\nfrom geopy.geocoders import Nominatim\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index(sqft=None, condition=None):\n location = None\n valuation = None\n if request.method == 'POST':\n if request.form['sqft']:\n sqft = request.form['sqft']\n condition = request.form['condition']\n waterfront_flag = 1 if request.form.get(\"waterfront\") == 'on' else 0\n address = request.form['address']\n below_grade = request.form['below_grade']\n if len(address) > 10:\n valuation, location = better_estimator(int(sqft), waterfront_flag, int(below_grade), address)\n else:\n valuation = ballpark_estimator(int(sqft), float(condition))\n\n return render_template('index2.html',\n sqft=sqft,\n condition=condition,\n location=location,\n valuation=valuation)\n\n\ndef ballpark_estimator(sqft=2080, condition=3.4):\n return -214216.30529291916 + 292.81216765 * sqft + 43037.62951553 * condition\n\n\n# put better_estimator code here\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=True)\n","sub_path":"tutorial/real_estate2.py","file_name":"real_estate2.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"82145772","text":"import collections\nfrom collections.abc import Sequence\n\nfrom supriya import CalculationRate\nfrom supriya.synthdefs import UGen\n\n\nclass Clip(UGen):\n \"\"\"\n Clips a signal outside given thresholds.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> clip = supriya.ugens.Clip.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> clip\n Clip.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"minimum\", 0.0), (\"maximum\", 1.0)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass Fold(UGen):\n \"\"\"\n Folds a signal outside given thresholds.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> fold = supriya.ugens.Fold.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> fold\n Fold.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"minimum\", 0.0), (\"maximum\", 1.0)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass Gate(UGen):\n \"\"\"\n Gates or holds.\n\n ::\n\n >>> source = supriya.ugens.WhiteNoise.ar()\n >>> trigger = supriya.ugens.Dust.kr(1)\n >>> gate = supriya.ugens.Gate.ar(source=source, trigger=trigger,)\n >>> gate\n Gate.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass InRange(UGen):\n \"\"\"\n Tests if a signal is within a given range.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> in_range = supriya.ugens.InRange.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> in_range\n InRange.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", 0), (\"minimum\", 0), (\"maximum\", 1)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass Latch(UGen):\n \"\"\"\n Samples and holds.\n\n ::\n\n >>> source = supriya.ugens.WhiteNoise.ar()\n >>> trigger = supriya.ugens.Dust.kr(1)\n >>> latch = supriya.ugens.Latch.ar(source=source, trigger=trigger,)\n >>> latch\n Latch.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass LeastChange(UGen):\n \"\"\"\n Outputs least changed input.\n\n ::\n\n >>> least_change = supriya.ugens.LeastChange.ar(a=0, b=0,)\n >>> least_change\n LeastChange.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"a\", 0), (\"b\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass MostChange(UGen):\n \"\"\"\n Outputs most changed input.\n\n ::\n\n >>> most_change = supriya.ugens.MostChange.ar(a=0, b=0,)\n >>> most_change\n MostChange.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"a\", 0), (\"b\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Peak(UGen):\n \"\"\"\n Tracks peak signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> peak = supriya.ugens.Peak.ar(source=source, trigger=trigger,)\n >>> peak\n Peak.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass PeakFollower(UGen):\n \"\"\"\n Tracks peak signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> peak_follower = supriya.ugens.PeakFollower.ar(decay=0.999, source=source,)\n >>> peak_follower\n PeakFollower.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"decay\", 0.999)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Phasor(UGen):\n \"\"\"\n A resettable linear ramp between two levels.\n\n ::\n\n >>> trigger = supriya.ugens.Impulse.kr(0.5)\n >>> phasor = supriya.ugens.Phasor.ar(\n ... rate=1, reset_pos=0, start=0, stop=1, trigger=trigger,\n ... )\n >>> phasor\n Phasor.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"trigger\", 0), (\"rate\", 1), (\"start\", 0), (\"stop\", 1), (\"reset_pos\", 0)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Poll(UGen):\n \"\"\"\n A UGen poller.\n\n ::\n\n >>> sine = supriya.ugens.SinOsc.ar()\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> poll = supriya.ugens.Poll.ar(source=sine, trigger=trigger, trigger_id=1234,)\n >>> poll\n Poll.ar()\n\n .. container:: example\n\n Unlike **sclang**, Python does not share any inter-process\n communication with **scsynth**. This means that the Poll UGen is not\n able to automatically print out its diagnostic messages into a Python\n interpreter session.\n\n To get information out of the Poll UGen, we first need to set the\n Poll's `trigger_id` to a value greater than 0. This will cause the poll\n to send `/tr` OSC messages back to its client - Python. We can then\n register a callback to respond to these `/tr` messages.\n\n ::\n\n >>> with supriya.SynthDefBuilder() as builder:\n ... sine = supriya.ugens.SinOsc.ar()\n ... trigger = supriya.ugens.Impulse.kr(1)\n ... poll = supriya.ugens.Poll.ar(source=sine, trigger=trigger, trigger_id=1234,)\n ...\n >>> synthdef = builder.build()\n\n ::\n\n >>> server = supriya.Server.default().boot()\n >>> synth = supriya.Synth(synthdef).allocate()\n >>> callback = server.osc_protocol.register(\n ... pattern=\"/tr\",\n ... procedure=lambda response: print(\n ... \"Poll value is: {}\".format(response.value)\n ... ),\n ... once=True,\n ... )\n\n ::\n\n >>> server.quit()\n \n\n \"\"\"\n\n ### CLASS VARIABLES ###\n\n __documentation_section__ = \"Utility UGens\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"trigger\", None), (\"source\", None), (\"trigger_id\", -1)]\n )\n\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n calculation_rate=None,\n label=None,\n source=None,\n trigger=None,\n trigger_id=-1,\n ):\n import supriya.synthdefs\n import supriya.ugens\n\n if label is None:\n if isinstance(source, supriya.synthdefs.UGen):\n label = type(source).__name__\n elif isinstance(source, supriya.synthdefs.OutputProxy):\n label = type(source.source).__name__\n UGen.__init__(\n self,\n calculation_rate=calculation_rate,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n label = str(label)\n self._configure_input(\"label\", len(label))\n for character in label:\n self._configure_input(\"label\", ord(character))\n\n ### PUBLIC METHODS ###\n\n @classmethod\n def ar(cls, label=None, source=None, trigger=None, trigger_id=-1):\n import supriya.synthdefs\n\n calculation_rate = supriya.CalculationRate.AUDIO\n ugen = cls._new_expanded(\n calculation_rate=calculation_rate,\n label=label,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n return ugen\n\n @classmethod\n def kr(cls, label=None, source=None, trigger=None, trigger_id=-1):\n import supriya.synthdefs\n\n calculation_rate = supriya.CalculationRate.CONTROL\n ugen = cls._new_expanded(\n calculation_rate=calculation_rate,\n label=label,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n return ugen\n\n @classmethod\n def new(cls, label=None, source=None, trigger=None, trigger_id=-1):\n import supriya.synthdefs\n\n if isinstance(source, Sequence):\n source = (source,)\n calculation_rates = []\n for single_source in source:\n rate = supriya.CalculationRate.from_expr(single_source)\n calculation_rates.append(rate)\n ugen = cls._new_expanded(\n calculation_rate=calculation_rates,\n label=label,\n source=source,\n trigger=trigger,\n trigger_id=trigger_id,\n )\n return ugen\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def label(self):\n \"\"\"\n Gets `label` input of Poll.\n\n ::\n\n >>> sine = supriya.ugens.SinOsc.ar()\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> poll = supriya.ugens.Poll.ar(\n ... label=\"Foo\", source=sine, trigger=trigger, trigger_id=1234,\n ... )\n >>> poll.label\n 'Foo'\n\n Returns ugen input.\n \"\"\"\n index = tuple(self._ordered_input_names).index(\"trigger_id\") + 2\n characters = self._inputs[index:]\n characters = [chr(int(_)) for _ in characters]\n label = \"\".join(characters)\n return label\n\n\nclass RunningMax(Peak):\n \"\"\"\n Tracks maximum signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> running_max = supriya.ugens.RunningMax.ar(source=source, trigger=0,)\n >>> running_max\n RunningMax.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass RunningMin(Peak):\n \"\"\"\n Tracks minimum signal amplitude.\n\n ::\n\n >>> source = supriya.ugens.In.ar(0)\n >>> trigger = supriya.ugens.Impulse.kr(1)\n >>> running_min = supriya.ugens.RunningMin.ar(source=source, trigger=trigger,)\n >>> running_min\n RunningMin.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None), (\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Schmidt(UGen):\n \"\"\"\n A Schmidt trigger.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> schmidt = supriya.ugens.Schmidt.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> schmidt\n Schmidt.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", 0), (\"minimum\", 0), (\"maximum\", 1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass SendPeakRMS(UGen):\n \"\"\"\n Tracks peak and power of a signal for GUI applications.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.kr(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms\n SendPeakRMS.kr()\n\n \"\"\"\n\n ### CLASS VARIABLES ###\n\n _default_channel_count = 0\n _ordered_input_names = collections.OrderedDict(\n [(\"reply_rate\", 20), (\"peak_lag\", 3), (\"reply_id\", -1)]\n )\n _unexpanded_argument_names = (\"source\",)\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n calculation_rate=None,\n command_name=\"/reply\",\n peak_lag=3,\n reply_id=-1,\n reply_rate=20,\n source=None,\n ):\n UGen.__init__(\n self,\n calculation_rate=calculation_rate,\n peak_lag=peak_lag,\n reply_id=reply_id,\n reply_rate=reply_rate,\n )\n command_name = str(command_name)\n if not isinstance(source, Sequence):\n source = (source,)\n self._configure_input(\"source\", len(source))\n for input_ in source:\n self._configure_input(\"source\", input_)\n self._configure_input(\"command_name\", len(command_name))\n for character in command_name:\n self._configure_input(\"label\", ord(character))\n\n ### PUBLIC METHODS ###\n\n @classmethod\n def ar(\n cls, command_name=\"/reply\", peak_lag=3, reply_id=-1, reply_rate=20, source=None\n ):\n \"\"\"\n Constructs an audio-rate SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.ar(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms\n SendPeakRMS.ar()\n\n Returns ugen graph.\n \"\"\"\n calculation_rate = CalculationRate.AUDIO\n ugen = cls._new_single(\n calculation_rate=calculation_rate,\n command_name=command_name,\n peak_lag=peak_lag,\n reply_id=reply_id,\n reply_rate=reply_rate,\n source=source,\n )\n return ugen\n\n @classmethod\n def kr(\n cls, command_name=\"/reply\", peak_lag=3, reply_id=-1, reply_rate=20, source=None\n ):\n \"\"\"\n Constructs a control-rate SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.kr(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms\n SendPeakRMS.kr()\n\n Returns ugen graph.\n \"\"\"\n calculation_rate = CalculationRate.CONTROL\n ugen = cls._new_single(\n calculation_rate=calculation_rate,\n command_name=command_name,\n peak_lag=peak_lag,\n reply_id=reply_id,\n reply_rate=reply_rate,\n source=source,\n )\n return ugen\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def command_name(self):\n \"\"\"\n Gets `command_name` input of SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.ar(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms.command_name\n '/reply'\n\n Returns ugen input.\n \"\"\"\n index = tuple(self._ordered_input_names).index(\"reply_id\") + 1\n source_length = int(self._inputs[index])\n index += source_length + 2\n characters = self._inputs[index:]\n characters = [chr(int(_)) for _ in characters]\n command_name = \"\".join(characters)\n return command_name\n\n @property\n def source(self):\n \"\"\"\n Gets `source` input of SendPeakRMS.\n\n ::\n\n >>> source = supriya.ugens.In.ar(channel_count=4)\n >>> send_peak_rms = supriya.ugens.SendPeakRMS.ar(\n ... command_name=\"/reply\",\n ... peak_lag=3,\n ... reply_id=-1,\n ... reply_rate=20,\n ... source=source,\n ... )\n >>> send_peak_rms.source\n (In.ar()[0], In.ar()[1], In.ar()[2], In.ar()[3])\n\n Returns ugen input.\n \"\"\"\n index = tuple(self._ordered_input_names).index(\"reply_id\") + 1\n source_length = int(self._inputs[index])\n start = index + 1\n stop = start + source_length\n return tuple(self._inputs[start:stop])\n\n\nclass SendTrig(UGen):\n _ordered_input_names = collections.OrderedDict(\n [(\"trigger\", None), (\"id_\", 0), (\"value\", 0)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Sweep(UGen):\n \"\"\"\n A triggered linear ramp.\n\n ::\n\n >>> sweep = supriya.ugens.Sweep.ar(rate=1, trigger=0,)\n >>> sweep\n Sweep.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"trigger\", 0), (\"rate\", 1)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass TDelay(UGen):\n \"\"\"\n A trigger delay.\n\n ::\n\n >>> source = supriya.ugens.Dust.kr()\n >>> tdelay = supriya.ugens.TDelay.ar(duration=0.1, source=source,)\n >>> tdelay\n TDelay.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"duration\", 0.1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass ToggleFF(UGen):\n \"\"\"\n A toggle flip-flop.\n\n ::\n\n >>> trigger = supriya.ugens.Dust.kr(1)\n >>> toggle_ff = supriya.ugens.ToggleFF.ar(trigger=trigger,)\n >>> toggle_ff\n ToggleFF.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"trigger\", 0)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Trig1(UGen):\n \"\"\"\n A timed trigger.\n\n ::\n\n >>> source = supriya.ugens.Dust.kr(1)\n >>> trig_1 = supriya.ugens.Trig1.ar(duration=0.1, source=source,)\n >>> trig_1\n Trig1.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"duration\", 0.1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Trig(UGen):\n \"\"\"\n A timed trigger.\n\n ::\n\n >>> source = supriya.ugens.Dust.kr(1)\n >>> trig = supriya.ugens.Trig.ar(duration=0.1, source=source,)\n >>> trig\n Trig.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", None), (\"duration\", 0.1)]\n )\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n\n\nclass Wrap(UGen):\n \"\"\"\n Wraps a signal outside given thresholds.\n\n ::\n\n >>> source = supriya.ugens.SinOsc.ar()\n >>> wrap = supriya.ugens.Wrap.ar(maximum=0.9, minimum=0.1, source=source,)\n >>> wrap\n Wrap.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict(\n [(\"source\", 0), (\"minimum\", 0), (\"maximum\", 1)]\n )\n _valid_calculation_rates = (\n CalculationRate.AUDIO,\n CalculationRate.CONTROL,\n CalculationRate.SCALAR,\n )\n\n\nclass ZeroCrossing(UGen):\n \"\"\"\n A zero-crossing frequency follower.\n\n ::\n\n >>> source = supriya.ugens.In.ar(bus=0)\n >>> zero_crossing = supriya.ugens.ZeroCrossing.ar(source=source,)\n >>> zero_crossing\n ZeroCrossing.ar()\n\n \"\"\"\n\n _ordered_input_names = collections.OrderedDict([(\"source\", None)])\n _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)\n","sub_path":"supriya/ugens/triggers.py","file_name":"triggers.py","file_ext":"py","file_size_in_byte":19351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"304223485","text":"from google_scholar_citations_count_retriever import QueryManipulator\nfrom unittest import TestCase\nfrom third_party.scholar import ScholarArticle\n\n\nclass GoogleScholarCitationsCountRetrieverTest(TestCase):\n\n def setUp(self):\n self.articles = [self.__create_scholar_article('Made up book, volume 1', 100),\n self.__create_scholar_article('Another made up book.', 124),\n self.__create_scholar_article('Made up book: vol I', 101),\n self.__create_scholar_article('This is a different book', 23)]\n\n self.expected_report = {'best_match_title': 'Made up book: vol I',\n 'best_match_num_citations': 101,\n 'articles_list': [\n {\n 'title': 'Made up book, volume 1',\n 'num_citations': 100,\n },\n {\n 'title': 'Another made up book.',\n 'num_citations': 124,\n },\n {\n 'title': 'Made up book: vol I',\n 'num_citations': 101,\n },\n {\n 'title': 'This is a different book',\n 'num_citations': 23,\n }\n ]}\n\n @staticmethod\n def __create_scholar_article(title, citations):\n article = ScholarArticle()\n article.attrs['title'][0] = title\n article.attrs['num_citations'][0] = citations\n return article\n\n def test_find_best_matching_article(self):\n query_manipulator = QueryManipulator('Made up book, volume 1', self.articles)\n best_match = query_manipulator.find_best_matching_article()\n self.assertEqual(best_match.attrs['title'][0], 'Made up book: vol I')\n\n query_manipulator = QueryManipulator('This is a different book.', self.articles)\n best_match = query_manipulator.find_best_matching_article()\n self.assertEqual(best_match.attrs['title'][0], 'This is a different book')\n\n def test_generate_report(self):\n query_manipulator = QueryManipulator('Made up book, volume 1', self.articles)\n report = query_manipulator.generate_report()\n self.assertEqual(report, self.expected_report)","sub_path":"python/test/google_scholar_citations_count_retriever_test.py","file_name":"google_scholar_citations_count_retriever_test.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"189699566","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author;鸿\nimport requests as r\nimport re\nimport time\nimport os\nword = str(input('请输入需要爬取图片的名称:'))\nurl = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&fm=index&pos=history&word={}'.format(word)\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'\n}\nresponse = r.get(url,headers=headers)\nhtml = response.text\n\nurls = re.findall('\"middleURL\":\"(.*?)\"',html)\nif not os.path.exists(word):\n os.mkdir(word)\ni=0\nfor url in urls:\n time.sleep(1)\n response = r.get(url,headers=headers)\n with open(word+'/'+str(i)+'.jpg','wb') as f:\n f.write(response.content)\n i+=1\nprint('爬取完成')","sub_path":"阶段一/百度图片爬取.py","file_name":"百度图片爬取.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"527063182","text":"\r\nfrom tkinter import *\r\nimport mysql.connector\r\nimport tkinter.messagebox as MessageBox\r\n\r\nmydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n\r\nprint(mydb)\r\n\r\nif(mydb):\r\n print(\"Connection successfull\")\r\n\r\nelse:\r\n print(\"Connection unsuccessfull\")\r\n\r\nmycursor=mydb.cursor()\r\n\r\n\r\n#creating the college table with coll_id as primary key\r\n\r\n## mycursor.execute(\" create table college(coll_id varchar(10) primary key,board varchar(10),accred varchar(10),state varchar(10),ranking int(10))\")\r\n\r\n#creating the department table with dept_id as primary key and the coll_id as foreign key\r\n\r\n## mycursor.execute(\"create table department (dept_id varchar(10) primary key,coll_id varchar(10) ,foreign key(coll_id) references college(coll_id) on delete cascade,hod_id varchar(10),instr_count int(10))\")\r\n\r\n\r\n#creating table instructor with dept_id as foreign key and instr_id as primary key\r\n\r\n## mycursor.execute(\"create table instructor(dept_id varchar(10) ,foreign key (dept_id) references department(dept_id) on delete cascade,instr_id varchar(10) primary key,rating int(10),qualification varchar(10))\")\r\n\r\n# create table courses with crc_id as primary_key and instr_id as foreign key\r\n\r\n## mycursor.execute(\"create table courses (crc_id varchar(10) primary key,instr_id varchar(10), foreign key(instr_id) references instructor(instr_id),std_count bigint(10))\")\r\n\r\n\r\n#create table student with std_id as primary key , crc_id and dept_id as foreign keys\r\n\r\n##mycursor.execute(\"create table student(std_id varchar(10) primary key,crc_id varchar(10),foreign key(crc_id) references courses(crc_id),dept_id varchar(10) , foreign key (dept_id) references department(dept_id),marks1 int(100),marks2 int(100),marks3 int(100),final_marks int (100))\")\r\n\r\n\r\n#mycursor.execute(\"Create table addresses(first_name text,last_name text,address text , city text , state text , zipcode int)\")\r\n\r\n\r\nmycursor.execute(\"show tables\")\r\nfor db in mycursor: \r\n print(db)\r\n\r\n\r\n\r\n\r\nTk, Label\r\nroot = Tk()\r\nroot.title('DBMS MINI PROJECT')\r\nroot.geometry(\"1000x1000\")\r\n\r\n# #create a submit function into the database \r\n\r\ndef insert():\r\n\r\n #to add data into the database we need to also add the creation of the database part ito the function\r\n \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #insert into the table \r\n coll_id_label=coll_id.get()\r\n board_label=board.get()\r\n accred_label=accred.get()\r\n state_label=state.get()\r\n ranking_label=ranking.get()\r\n\r\n mycursor.execute(\"insert into college values('\"+coll_id_label + \"' , '\"+board_label + \"' , '\"+accred_label + \"', '\"+state_label + \"','\"+ ranking_label + \"')\")\r\n \r\n \r\n\r\n #clear the text boxes\r\n coll_id.delete(0,END)\r\n board.delete(0,END)\r\n accred.delete(0,END)\r\n state.delete(0,END)\r\n ranking.delete(0,END)\r\n \r\n \r\n\r\n mydb.commit()\r\n MessageBox.showinfo(\"Inserted Status\",\"Inserted Successfully\")\r\n show()\r\n mydb.close()\r\n \r\n#\r\ndef delete():\r\n\r\n #delete from the table \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #execute the query\r\n coll_id_label=coll_id.get()\r\n mycursor.execute(\"delete from college where coll_id='\"+coll_id_label+\"'\")\r\n \r\n coll_id.delete(0,END)\r\n board.delete(0,END)\r\n accred.delete(0,END)\r\n state.delete(0,END)\r\n ranking.delete(0,END)\r\n mydb.commit()\r\n MessageBox.showinfo(\"Deleted Status\",\"Deleted Successfully\")\r\n show()\r\n \r\n mydb.close()\r\n \r\n\r\n\r\ndef update():\r\n \r\n #insert into the table \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #insert into the table \r\n coll_id_label=coll_id.get()\r\n board_label=board.get()\r\n accred_label=accred.get()\r\n state_label=state.get()\r\n ranking_label=ranking.get()\r\n \r\n mycursor.execute('''UPDATE college SET board=%s ,accred =%s ,state =%s ,ranking=%s where coll_id=%s''',(board_label ,accred_label ,state_label,ranking_label ,coll_id_label) )\r\n # mycursor.execute(\"update college set board_label='\"+board_label + \"',accred_label='\"+accred_label + \"',state_label= '\"+state_label + \"',ranking_label='\"+ ranking_label + \"' where coll_id_label='\"+ coll_id_label +\"'\")\r\n \r\n coll_id.delete(0,END)\r\n board.delete(0,END)\r\n accred.delete(0,END)\r\n state.delete(0,END)\r\n ranking.delete(0,END)\r\n \r\n mydb.commit()\r\n MessageBox.showinfo(\"Update Status\",\"Updated Successfully\")\r\n show()\r\n mydb.close()\r\n \r\n\r\n #clear the text boxes\r\n \r\n\r\n\r\ndef get():\r\n \r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n\r\n #execute the query\r\n coll_id_label=coll_id.get()\r\n mycursor.execute(\"select * from college where coll_id='\"+coll_id_label+\"'\")\r\n rows = mycursor.fetchall()\r\n for row in rows:\r\n board.insert(0,row[1])\r\n accred.insert(0,row[2])\r\n state.insert(0,row[3])\r\n ranking.insert(0,row[4]) \r\n \r\n \r\n mydb.commit()\r\n mydb.close()\r\n\r\ndef show():\r\n mydb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"root\",database=\"dbproject\")\r\n mycursor=mydb.cursor()\r\n mycursor.execute(\"select * from college\")\r\n rows=mycursor.fetchall()\r\n list.delete(0, list.size())\r\n\r\n for row in rows:\r\n insertData = row[0]+ ' | ' + row[1] + ' | ' + row[2] + ' | ' + row[3] + ' | ' + str(row[4])\r\n list.insert(list.size()+1 , insertData)\r\n\r\n mydb.commit()\r\n mydb.close()\r\n\r\ncoll_id=Entry(root,width=30)\r\ncoll_id.place(x=150,y=30)\r\n\r\n\r\nboard=Entry(root,width=30)\r\nboard.place(x=150,y=60)\r\n\r\naccred=Entry(root,width=30)\r\naccred.place(x=150,y=90)\r\n\r\nstate=Entry(root,width=30)\r\nstate.place(x=150,y=120)\r\n\r\nranking=Entry(root,width=30)\r\nranking.place(x=150,y=150)\r\n\r\n\r\n\r\n# Create text box label for college table \r\n\r\ncoll_id_label=Label(root , text=\"College Id\")\r\ncoll_id_label.place(x=20,y=30)\r\n\r\n\r\nboard_label=Label(root , text=\"Board\")\r\nboard_label.place(x=20,y=60)\r\n\r\naccred_label=Label(root , text=\"Accredation\")\r\naccred_label.place(x=20,y=90)\r\n\r\nstate_label=Label(root , text=\"State\")\r\nstate_label.place(x=20,y=120)\r\n\r\nranking_label=Label(root , text=\"Ranking\")\r\nranking_label.place(x=20,y=150)\r\n\r\n\r\n# # create a submit button\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ninsert = Button(root , text=\"insert\" , command=insert)\r\ninsert.place(x=50,y=180)\r\n\r\ndelete = Button(root , text=\"Delete \" , command=delete)\r\ndelete.place(x=100,y=180)\r\n\r\nupdate = Button(root , text=\"Update \" , command=update)\r\nupdate.place(x=160,y=180)\r\n\r\nget = Button(root , text=\"get\" , command=get)\r\nget.place(x=220,y=180)\r\n\r\nlist = Listbox(root)\r\nlist.place(x=350 , y=20)\r\nshow()\r\nroot.mainloop()\r\n","sub_path":"college.py","file_name":"college.py","file_ext":"py","file_size_in_byte":6917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"153957373","text":"# https://www.hackerrank.com/challenges/dynamic-array/problem\n# Create a list, seqList, of N empty sequences, where each sequence is indexed from 0 to N.\n# The elements within each of the sequences also use 0-indexing.\n# Create an integer, lastAnswer, and initialize it to 0.\nfile_ = '03.txt'\nseqList = []\nlastAnswer = 0\n\nwith open(file_, 'r') as inputs:\n data = inputs.readlines()\n n, q = map(int, data[0].split(' '))\n inputs.close()\n\nfor i in range(n):\n seqList.append([])\n\ndef query_one(x, y, n, last_answer):\n temp_index = (x ^ last_answer) % n\n seqList[temp_index].append(y)\n\ndef query_two(x, y, n, last_answer):\n temp_index = (x ^ last_answer) % n\n seq = seqList[temp_index]\n last_answer = seqList[temp_index][y % len(seq)]\n return last_answer\n\nfor i in range(q):\n query, x, y = map(int, data[i+1].split(' '))\n if query == 1:\n query_one(x, y, n, lastAnswer)\n elif query == 2:\n lastAnswer = query_two(x, y, n, lastAnswer)\n print(lastAnswer)","sub_path":"Arrays/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"593954304","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom datetime import datetime, timedelta\n\nfrom django.conf import settings\nfrom dimagi.utils.chunked import chunked\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext as _\nfrom django.urls import reverse\nfrom memoized import memoized\n\nfrom corehq.elastic import ES_MAX_CLAUSE_COUNT\nfrom corehq.apps.es.case_search import flatten_result\nfrom corehq.apps.locations.models import SQLLocation\nfrom corehq.apps.sms.models import MessagingEvent\nfrom casexml.apps.case.models import CommCareCase\nfrom corehq.motech.repeaters.dbaccessors import (\n iter_repeat_records_by_domain,\n get_repeat_record_count,\n get_repeat_records_by_payload_id,\n get_repeaters_by_domain,\n)\nfrom corehq.motech.repeaters.views import DomainForwardingRepeatRecords\nfrom corehq.apps.es import CaseSearchES\nfrom corehq.apps.reports.generic import GenericTabularReport\nfrom corehq.apps.reports.filters.select import RepeaterFilter\nfrom corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn\n\nfrom custom.enikshay.case_utils import get_person_case, CASE_TYPE_VOUCHER\nfrom custom.enikshay.exceptions import ENikshayException\nfrom custom.enikshay.reports.filters import VoucherStateFilter, DistrictLocationFilter, VoucherIDFilter\nfrom custom.enikshay.integrations.bets.repeaters import ChemistBETSVoucherRepeater, LabBETSVoucherRepeater\nfrom corehq.apps.reports.dispatcher import CustomProjectReportDispatcher\nfrom corehq.apps.reports.filters.select import RepeatRecordStateFilter\nfrom dimagi.utils.modules import to_function\n\n\nclass ENikshayRepeaterFilter(RepeaterFilter):\n\n def __init__(self, *args, **kwargs):\n super(ENikshayRepeaterFilter, self).__init__(*args, **kwargs)\n self.enikshay_repeaters = tuple(to_function(cls, failhard=True) for cls in settings.ENIKSHAY_REPEATERS)\n\n def _get_repeaters(self):\n return [\n repeater for repeater in get_repeaters_by_domain(self.domain)\n if isinstance(repeater, self.enikshay_repeaters)\n ]\n\n\nclass ENikshayForwarderReport(DomainForwardingRepeatRecords):\n name = 'eNikshay Forwarder Report'\n base_template = 'reports/base_template.html'\n asynchronous = True\n section_name = 'Custom Reports'\n slug = 'enikshay_repeater_report'\n dispatcher = CustomProjectReportDispatcher\n fields = (ENikshayRepeaterFilter, RepeatRecordStateFilter)\n exportable = True\n exportable_all = True\n\n emailable = True\n\n @property\n def get_all_rows(self):\n repeater_id = self.request.GET.get('repeater', None)\n state = self.request.GET.get('record_state', None)\n if self.is_rendered_as_email:\n same_time_yesterday = datetime.today() - timedelta(days=1)\n return [\n [\n get_repeat_record_count(self.domain, repeater_id, \"SUCCESS\"),\n get_repeat_record_count(self.domain, repeater_id, \"SUCCESS\", same_time_yesterday),\n get_repeat_record_count(self.domain, repeater_id, \"CANCELLED\"),\n get_repeat_record_count(self.domain, repeater_id, \"CANCELLED\", same_time_yesterday),\n ]\n ]\n return [self._make_row(record) for record in\n iter_repeat_records_by_domain(self.domain, repeater_id=repeater_id, state=state)]\n\n @property\n def headers(self):\n if self.is_rendered_as_email:\n columns = [\n DataTablesColumn(_('Successful Records')),\n DataTablesColumn(_('Successful Records in Last 24 hours')),\n DataTablesColumn(_('Cancelled Records')),\n DataTablesColumn(_('Cancelled Records in Last 24 hours')),\n ]\n else:\n columns = [\n DataTablesColumn(_('Record ID')),\n DataTablesColumn(_('Status')),\n DataTablesColumn(_('Person Case')),\n DataTablesColumn(_('Payload Case')),\n DataTablesColumn(_('URL')),\n DataTablesColumn(_('Last sent date')),\n DataTablesColumn(_('Attempts')),\n ]\n return DataTablesHeader(*columns)\n\n def _make_row(self, record):\n attempt_messages = [\n escape(\"{date}: {message}\".format(\n date=self._format_date(attempt.datetime),\n message=attempt.message))\n for attempt in record.attempts]\n\n row = [\n record._id,\n self._get_state(record)[1],\n self._get_person_id_link(record),\n self._get_case_id_link(record.payload_id),\n record.url if record.url else _('Unable to generate url for record'),\n self._format_date(record.last_checked) if record.last_checked else '---',\n \", \".join(attempt_messages),\n ]\n return row\n\n def _get_person_id_link(self, record):\n try:\n person_id = get_person_case(self.domain, record.payload_id).case_id\n return self._get_case_id_link(person_id)\n except ENikshayException as error:\n return \"Error: {}\".format(error)\n\n def _get_case_id_link(self, case_id):\n return '{case_id} '.format(\n url=reverse('case_data', args=[self.domain, case_id]),\n case_id=case_id\n )\n\n\nclass ENikshayVoucherReport(GenericTabularReport):\n slug = 'enikshay_voucher_repeater_report'\n section_name = 'Custom Reports'\n name = 'BETS Voucher Report'\n\n base_template = 'reports/base_template.html'\n dispatcher = CustomProjectReportDispatcher\n exportable = True\n exportable_all = True\n\n asynchronous = True\n ajax_pagination = True\n\n sortable = False\n\n fields = (VoucherStateFilter, DistrictLocationFilter, VoucherIDFilter)\n\n @property\n def district_ids(self):\n return self.request.GET.getlist('district_ids')\n\n @property\n def voucher_state(self):\n return self.request.GET.get('voucher_state')\n\n @property\n def voucher_id(self):\n return self.request.GET.get('voucher_id')\n\n @property\n def headers(self):\n return DataTablesHeader(\n DataTablesColumn('Voucher Case ID'),\n DataTablesColumn('Voucher Readable ID'),\n DataTablesColumn('Voucher Status'),\n DataTablesColumn('Voucher District ID'),\n DataTablesColumn('Voucher Type'),\n DataTablesColumn('Voucher Approved Amount'),\n DataTablesColumn('Voucher Beneficiary ID'),\n DataTablesColumn('Voucher Beneficiary Name'),\n DataTablesColumn('Voucher Issued by Name'),\n\n DataTablesColumn('Amount Paid'),\n DataTablesColumn('Date Paid'),\n DataTablesColumn('Comments'),\n DataTablesColumn('Payment Mode'),\n DataTablesColumn('Check Number'),\n DataTablesColumn('Bank Name'),\n DataTablesColumn('Reason Rejected'),\n DataTablesColumn('Date Rejected'),\n DataTablesColumn('Messaging Activity'),\n\n DataTablesColumn('BETS Sent Date'),\n DataTablesColumn('Forwading Status'),\n DataTablesColumn('BETS Response Message'),\n )\n\n @property\n def rows(self):\n return self.get_rows(paged=True)\n\n @property\n def get_all_rows(self):\n return self.get_rows(paged=False)\n\n def get_rows(self, paged=True):\n location_ids = self._get_voucher_location_ids()\n if location_ids:\n vouchers = []\n for location_id_chunk in chunked(location_ids, ES_MAX_CLAUSE_COUNT):\n vouchers += [\n CommCareCase.wrap(flatten_result(result))\n for result in self._search_results(paged, location_id_chunk).raw_hits\n ]\n else:\n vouchers = [\n CommCareCase.wrap(flatten_result(result))\n for result in self._search_results(paged).raw_hits\n ]\n\n return [row for voucher in vouchers for row in self._make_rows(voucher)]\n\n @memoized\n def _search_results(self, paged=True, location_ids=None):\n cs = (\n CaseSearchES()\n .domain(self.domain)\n .case_type(CASE_TYPE_VOUCHER)\n )\n\n if location_ids:\n cs = cs.case_property_query('voucher_fulfilled_by_location_id', \" \".join(location_ids))\n\n if self.voucher_state:\n cs = cs.case_property_query('state', self.voucher_state)\n\n if self.voucher_id:\n cs = cs.case_property_query('voucher_id', self.voucher_id)\n\n if paged:\n cs = cs.start(self.pagination.start).size(self.pagination.count)\n\n return cs.run()\n\n @memoized\n def _get_voucher_location_ids(self):\n \"\"\"Return all locations beneath the district that could own the voucher\n \"\"\"\n district_locs = SQLLocation.active_objects.filter(location_id__in=self.district_ids)\n voucher_location_types = ['plc', 'pcc', 'pdr', 'dto']\n possible_location_ids = (\n SQLLocation.active_objects\n .get_queryset_descendants(district_locs, include_self=True)\n .filter(location_type__code__in=voucher_location_types)\n .values_list('location_id', flat=True)\n )\n return possible_location_ids\n\n def get_messaging_event_detail_link(self, messaging_event_id):\n return (\n '[%s] ' %\n (self.domain, messaging_event_id, messaging_event_id)\n )\n\n def get_messaging_event_links(self, voucher_case_id):\n event_pks = (\n MessagingEvent\n .objects\n .filter(domain=self.domain, messagingsubevent__case_id=voucher_case_id)\n .values_list('pk', flat=True)\n .distinct()\n .order_by('date')\n )\n\n return ', '.join([self.get_messaging_event_detail_link(pk) for pk in event_pks])\n\n def _make_rows(self, voucher):\n default_row = [\n voucher.case_id,\n voucher.get_case_property('voucher_id'),\n voucher.get_case_property('state'),\n voucher.get_case_property('voucher_district_id'),\n voucher.get_case_property('voucher_type'),\n voucher.get_case_property('amount_approved'),\n voucher.get_case_property('voucher_fulfilled_by_id'),\n voucher.get_case_property('voucher_fulfilled_by_name'),\n voucher.get_case_property('voucher_issued_by_name'),\n voucher.get_case_property('amount_paid'),\n voucher.get_case_property('date_paid'),\n voucher.get_case_property('comments'),\n voucher.get_case_property('payment_mode'),\n voucher.get_case_property('check_number'),\n voucher.get_case_property('bank_name'),\n voucher.get_case_property('reason_rejected'),\n voucher.get_case_property('date_rejected'),\n self.get_messaging_event_links(voucher.case_id),\n ]\n\n repeat_records = self._get_voucher_repeat_records(voucher.case_id)\n if not repeat_records:\n return [default_row + [\"-\", \"-\", \"-\"]]\n\n rows = []\n for repeat_record in repeat_records:\n attempt_messages = [\n escape(\"{date}: {message}\".format(\n date=attempt.datetime,\n message=attempt.message))\n for attempt in repeat_record.attempts\n ]\n rows.append(\n default_row + [\n repeat_record.last_checked if repeat_record.last_checked else '-',\n repeat_record.state,\n \", \".join(attempt_messages),\n ]\n )\n return rows\n\n def _get_voucher_repeat_records(self, voucher_id):\n repeat_records = get_repeat_records_by_payload_id(self.domain, voucher_id)\n return [r for r in repeat_records if r.repeater_id in self._get_voucher_repeater_ids()]\n\n def _get_voucher_repeater_ids(self):\n return [\n repeater._id for repeater in get_repeaters_by_domain(self.domain)\n if isinstance(repeater, (LabBETSVoucherRepeater, ChemistBETSVoucherRepeater))\n ]\n\n @property\n def total_records(self):\n location_ids = self._get_voucher_location_ids()\n if location_ids:\n total = 0\n for location_id_chunk in chunked(location_ids, ES_MAX_CLAUSE_COUNT):\n total += self._search_results(location_ids=location_id_chunk).total\n else:\n total = self._search_results().total\n return total\n\n @property\n def shared_pagination_GET_params(self):\n return [\n dict(name='district_ids', value=self.district_ids),\n dict(name='voucher_state', value=self.voucher_state),\n dict(name='voucher_id', value=self.voucher_id),\n ]\n","sub_path":"custom/enikshay/reports/repeaters.py","file_name":"repeaters.py","file_ext":"py","file_size_in_byte":13009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"226615743","text":"#!/usr/bin/env python\n\nimport json, argparse\nfrom datetime import datetime, timezone\n# external:\nimport dateparser\nfrom matplotlib import pyplot as plt\n\ndef dateutil_parse_local(point_in_time: str):\n dt = dateparser.parse(point_in_time)\n return dt\n\ndef dateutil_parse_utc(point_in_time: str):\n dt = dateparser.parse(point_in_time, settings={'TIMEZONE': 'UTC'})\n return dt.replace(tzinfo=timezone.utc)\n\n# general metrics\nGEN = []\nwith open(\"metrics_gen.jsonl\", \"rt\") as f:\n for line in f.readlines():\n GEN.append(json.loads(line))\n # example chunk:\n #{'data': [{'capacityUtilized': 'N/A',\n # 'connectedPVCount': '27112',\n # 'dataRate': '586,518.88',\n # 'dataRateGBPerDay': '47.19',\n # 'dataRateGBPerYear': '17,226.17',\n # 'disconnectedPVCount': '9470',\n # 'eventRate': '28,665.56',\n # 'formattedWriteThreadSeconds': '0.49',\n # 'instance': 'appliance0',\n # 'maxETLPercentage': '0',\n # 'pvCount': '36582',\n # 'secondsConsumedByWritter': '0.48627441860465126',\n # 'status': 'Working',\n # 'timeForOverallETLInSeconds(0)': '0',\n # 'timeForOverallETLInSeconds(1)': '0',\n # 'totalETLRuns(0)': '0',\n # 'totalETLRuns(1)': '0'}],\n # 'duration': 0.028889894485473633,\n # 'start': 1601028901.436821}\n\n# detailed metrics\nDET = []\nwith open(\"metrics_det.jsonl\", \"rt\") as f:\n for line in f.readlines():\n DET.append(json.loads(line))\n #{'data': [{'name': 'Appliance Identity',\n # 'source': 'mgmt',\n # 'value': 'appliance0'},\n # {'name': 'Total PV count', 'source': 'engine', 'value': '2103'},\n # {'name': 'Disconnected PV count', 'source': 'engine', 'value': '0'},\n # {'name': 'Connected PV count', 'source': 'engine', 'value': '2103'},\n # {'name': 'Paused PV count', 'source': 'engine', 'value': '0'},\n # {'name': 'Total channels', 'source': 'engine', 'value': '16824'},\n # {'name': 'Approx pending jobs in engine queue',\n # 'source': 'engine',\n # 'value': '1'},\n # {'name': 'Event Rate (in events/sec)',\n # 'source': 'engine',\n # 'value': '2,093.91'},\n # {'name': 'Data Rate (in bytes/sec)',\n # 'source': 'engine',\n # 'value': '46,975.96'},\n # {'name': 'Data Rate in (GB/day)',\n # 'source': 'engine',\n # 'value': '3.78'},\n # {'name': 'Data Rate in (GB/year)',\n # 'source': 'engine',\n # 'value': '1,379.69'},\n # {'name': 'Time consumed for writing samplebuffers to STS (in secs)',\n # 'source': 'engine',\n # 'value': '0.1'},\n # {'name': 'Benchmark - writing at (events/sec)',\n # 'source': 'engine',\n # 'value': '216,425.2'},\n # {'name': 'Benchmark - writing at (MB/sec)',\n # 'source': 'engine',\n # 'value': '4.63'},\n # {'name': 'PVs pending computation of meta info',\n # 'source': 'engine',\n # 'value': '0'},\n # {'name': 'Total number of reference counted channels',\n # 'source': 'engine',\n # 'value': '2103'},\n # {'name': 'Total number of CAJ channels',\n # 'source': 'engine',\n # 'value': '2103'},\n # {'name': 'Channels with pending search requests',\n # 'source': 'engine',\n # 'value': '0 of 2103'},\n # {'name': 'PVs in archive workflow',\n # 'source': 'mgmt',\n # 'value': '18753'},\n # {'name': 'Capacity planning last update',\n # 'source': 'mgmt',\n # 'value': 'Sep/25/2020 10:41:38 +00:00'},\n # {'name': 'Engine write thread usage', 'source': 'mgmt', 'value': '0'},\n # {'name': 'Aggregated appliance storage rate (in GB/year)',\n # 'source': 'mgmt',\n # 'value': '5,950.75'},\n # {'name': 'Aggregated appliance event rate (in events/sec)',\n # 'source': 'mgmt',\n # 'value': '10,129.47'},\n # {'name': 'Aggregated appliance PV count',\n # 'source': 'mgmt',\n # 'value': '10,000'},\n # {'name': 'Incremental appliance storage rate (in GB/year)',\n # 'source': 'mgmt',\n # 'value': '5,950.75'},\n # {'name': 'Incremental appliance event rate (in events/sec)',\n # 'source': 'mgmt',\n # 'value': '10,129.47'},\n # {'name': 'Incremental appliance PV count',\n # 'source': 'mgmt',\n # 'value': '10,000'}],\n # 'duration': 0.0041654109954833984,\n # 'start': 1601031014.5272684}\n\n# memory metrics\nMEM = []\nwith open(\"metrics_mem.jsonl\", \"rt\") as f:\n for line in f.readlines():\n MEM.append(json.loads(line))\n #{'data': [{'data': [[1601198632000, 2.54],\n # [1601203852000, 18.47],\n # [1601203912000, 17.61]],\n # 'label': 'system_load (%)'},\n # {'data': [[1601198632000, 5.784291436430067],\n # [1601198993000, 35.940306703560054],\n # [1601203912000, 23.69133603060618]],\n # 'label': 'engine_heap (%)'},\n # {'data': [[1601198633000, 5.833119561430067],\n # [1601198933000, 24.62394153699279],\n # [1601203913000, 27.25578915560618]],\n # 'label': 'etl_heap (%)'},\n # {'data': [[1601198635000, 5.881947686430067],\n # [1601198695000, 16.95973655441776],\n # [1601203915000, 21.66814556112513]],\n # 'label': 'retrieval_heap (%)'}],\n # 'duration': 0.0038259029388427734,\n # 'start': 1601203959.5360134}\n\ndef get_args():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--start', '-s', type=dateutil_parse_local)\n parser.add_argument('--end', '-e', type=dateutil_parse_local)\n return parser.parse_args()\n\nargs = get_args()\n\ndef filter_start_end(ds, start=None, end=None):\n if args.start:\n ds = [chunk for chunk in ds if chunk[\"start\"] > args.start.timestamp()]\n if args.end:\n ds = [chunk for chunk in ds if chunk[\"start\"] < args.end.timestamp()]\n return ds\n\ndef convert_start_to_datetime(ds):\n for chunk in ds:\n #chunk[\"start\"] = datetime.utcfromtimestamp(chunk[\"start\"])\n chunk[\"start\"] = datetime.fromtimestamp(chunk[\"start\"])\n return ds\n\nGEN = convert_start_to_datetime(filter_start_end(GEN, args.start, args.end))\nDET = convert_start_to_datetime(filter_start_end(DET, args.start, args.end))\nMEM = convert_start_to_datetime(filter_start_end(MEM, args.start, args.end))\n\nplots = [\n {\n 'slug': 'duration-vs-time',\n 'title': 'duration plottet against date/time',\n 'method': 'plot',\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: chunk[\"duration\"],\n },\n {\n 'slug': 'disconnectedPVCount-vs-totalPVcount',\n 'method': 'scatter',\n 'x': lambda chunk: int(chunk[\"data\"][0][\"pvCount\"]),\n 'y': lambda chunk: int(chunk[\"data\"][0][\"disconnectedPVCount\"]),\n },\n {\n 'slug': 'secondsConsumedByWritter-vs-connectedPVCount',\n 'x': lambda chunk: int(chunk[\"data\"][0][\"connectedPVCount\"]),\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"secondsConsumedByWritter\"]),\n },\n {\n 'slug': 'secondsConsumedByWritter-vs-eventRate',\n 'x': lambda chunk: flt(chunk[\"data\"][0][\"eventRate\"]),\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"secondsConsumedByWritter\"]),\n },\n {\n 'slug': 'connectedPVCount-vs-start',\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: int(chunk[\"data\"][0][\"connectedPVCount\"]),\n },\n {\n 'slug': 'secondsConsumedByWritter-vs-start',\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"secondsConsumedByWritter\"]),\n },\n {\n 'slug': 'dataRate-vs-connectedPVCount',\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: int(chunk[\"data\"][0][\"connectedPVCount\"]),\n 'y': lambda chunk: flt(chunk[\"data\"][0][\"dataRate\"]),\n },\n {\n 'slug': \"benchmarkEventsPerS-vs-start\",\n 'data': DET,\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: flt(choose(chunk[\"data\"], \"Benchmark - writing at (events/sec)\", \"nan\")),\n },\n {\n 'slug': \"pvs-in-archive-workflow--vs--start\",\n 'data': DET,\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: int(choose(chunk[\"data\"], \"PVs in archive workflow\")),\n },\n {\n 'slug': \"pending-vs-start\",\n 'data': DET,\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: chunk[\"start\"],\n 'y': lambda chunk: int(choose(chunk[\"data\"], \"Channels with pending search requests\", \"0 of 0\").partition(\" of \")[0]),\n },\n {\n 'slug': \"pending-vs-total\",\n 'data': DET,\n 'method': 'scatter',\n 'method_kwargs': {'s': 0.4},\n 'x': lambda chunk: int(choose(chunk[\"data\"], \"Channels with pending search requests\", \"0 of 0\").partition(\" of \")[2]),\n 'y': lambda chunk: int(choose(chunk[\"data\"], \"Channels with pending search requests\", \"0 of 0\").partition(\" of \")[0]),\n },\n {\n 'slug': \"system_load\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"system_load (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"system_load (%)\", lambda x: x[\"data\"][-1][1]),\n },\n {\n 'slug': \"engine_heap\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"engine_heap (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"engine_heap (%)\", lambda x: x[\"data\"][-1][1]),\n },\n {\n 'slug': \"etl_heap\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"etl_heap (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"etl_heap (%)\", lambda x: x[\"data\"][-1][1]),\n },\n {\n 'slug': \"retrieval_heap\",\n 'data': MEM,\n 'x': lambda chunk: datetime.fromtimestamp(first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"retrieval_heap (%)\", lambda x: x[\"data\"][-1][0])/1000),\n 'y': lambda chunk: first_matching_from_iterable(chunk[\"data\"], lambda x: x[\"label\"] == \"retrieval_heap (%)\", lambda x: x[\"data\"][-1][1]),\n },\n\n]\n\ndef flt(val):\n return float(val.replace(\",\", \"\"))\n\ndef first_matching_from_iterable(candidates, match_func, extract_func=None):\n for candidate in candidates:\n if match_func(candidate):\n # we found our match\n if extract_func:\n return extract_func(candidate)\n else:\n return candidate\n raise ValueError(\"No match found\")\n\ndef choose(iterable, name, if_not_found=None):\n try:\n return first_matching_from_iterable(iterable, lambda x: x[\"name\"] == name, lambda x: x[\"value\"])\n except ValueError:\n return if_not_found\n\nfor plot in plots:\n print(plot.get(\"title\", plot.get(\"slug\")))\n # we have the following data sources: GEN, DET, MEM; default is GEN\n data = plot.get(\"data\", GEN)\n x = [plot[\"x\"](chunk) for chunk in data]\n y = [plot[\"y\"](chunk) for chunk in data]\n plt.figure(figsize=(10, 6))\n plt.title(plot.get(\"title\", plot.get(\"slug\")))\n method = plot.get(\"method\", \"plot\")\n getattr(plt, method)(x, y, **plot.get(\"method_kwargs\", {}))\n plt.savefig(f\"plots/{plot['slug']}.png\", dpi=200)\n plt.show()\n","sub_path":"plot_data.py","file_name":"plot_data.py","file_ext":"py","file_size_in_byte":12619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"56151252","text":" # -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 22 14:58:07 2019\n\n@author: Shachar\n\"\"\"\n\n#read from Excel the syllables, their type and their scores.\n#The function performs pre-processing: remove DC, padding zeros, decimation and normalization.\n# Returns: image, score, and true value\n#Pay attention to line 27 and 36 (path of file)\n\n\n\ndef ReadingAudio():\n import scipy\n from scipy import signal\n from scipy.io import wavfile\n from pathlib import Path\n import numpy as np\n from scipy.misc import imresize\n import xlrd\n from AudioPreProcessing import AudioPreProcessing\n from skimage import img_as_ubyte\n \n # Open the gold standard xl\n xl_workbook = xlrd.open_workbook(r\"C:\\Users\\yaniv\\Desktop\\project2019\\May\\gold standars.xlsx\")\n xl_sheet = xl_workbook.sheet_by_index(0)\n \n num_rows = xl_sheet.nrows # Number of rows\n \n Rec_path = 'E:/Recordings/Adult/2017' #yaniv\n \n Image = [None] * num_rows\n TrueLabels = [None] * num_rows\n Data = [None] * num_rows\n Precentages = [None] * num_rows\n for row_idx in range(1,num_rows): # Iterate through rows\n current_row = xl_sheet.row_values(row_idx)\n data_folder = Path(Rec_path + \"/%s relevant/%s/ch1\" %(current_row[2], current_row[1]))\n file = \"%s.wav\" %(current_row[3])\n file_to_open = data_folder / file\n sample_rate, samples = wavfile.read(file_to_open)\n PreProcessedAudio=AudioPreProcessing(sample_rate, samples)\n frequencies, times, spectrogram = signal.spectrogram(PreProcessedAudio, sample_rate)\n list_times=list( times)\n first_num = times[times>=current_row[4]][0]\n first_ind = list_times.index(first_num)\n sec_num = times[times>=current_row[5]][0]\n sect_ind = list_times.index(sec_num)\n x=spectrogram[:,first_ind:sect_ind]\n \n # DC removal\n x-=scipy.mean(x)\n \n # zero padding to size 200\n size=400\n c,r=np.shape(x)\n padr1=int((size-r)/2)\n padr2=size-r-padr1\n padc1=int((size-c)/2)\n padc2=size-c-padc1\n Padded=np.pad(x, [(padc1, padc2), (padr1, padr2)], mode='constant')\n \n # Decimation to a size of (32,32)\n DecIm=imresize(Padded, (32,32), interp='bilinear', mode=None)\n # from PIL import Image\n\n # DecIm = np.array(Image.fromarray(Padded).resize([32,32],resample = Image.BILINEAR)) \n\n # normalization\n img=DecIm/np.amax(DecIm)\n # Data[row_idx] = img\n\n Data[row_idx] = img_as_ubyte(img)\n TrueLabels[row_idx] = current_row[6]\n Precentages[row_idx] = current_row[7]\n Image[row_idx] = x\n \n return(Data,TrueLabels,Precentages,Image)\n","sub_path":"Reading data and preprocessing/ReadingAudio.py","file_name":"ReadingAudio.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"521711172","text":"# # ⚠ Warning\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# [🥭 Mango Markets](https://mango.markets/) support is available at:\n# [Docs](https://docs.mango.markets/)\n# [Discord](https://discord.gg/67jySBhxrg)\n# [Twitter](https://twitter.com/mangomarkets)\n# [Github](https://github.com/blockworks-foundation)\n# [Email](mailto:hello@blockworks.foundation)\n\nimport typing\n\nfrom decimal import Decimal\nfrom pyserum.market import Market as PySerumMarket\nfrom solana.publickey import PublicKey\n\nfrom .account import Account\nfrom .combinableinstructions import CombinableInstructions\nfrom .context import Context\nfrom .group import Group\nfrom .instructions import build_serum_consume_events_instructions, build_spot_place_order_instructions, build_cancel_spot_order_instructions, build_spot_settle_instructions, build_spot_openorders_instructions\nfrom .marketinstructionbuilder import MarketInstructionBuilder\nfrom .orders import Order\nfrom .publickey import encode_public_key_for_sorting\nfrom .spotmarket import SpotMarket\nfrom .tokenaccount import TokenAccount\nfrom .wallet import Wallet\n\n\n# # 🥭 SpotMarketInstructionBuilder\n#\n# This file deals with building instructions for Spot markets.\n#\n# As a matter of policy for all InstructionBuidlers, construction and build_* methods should all work with\n# existing data, requiring no fetches from Solana or other sources. All necessary data should all be loaded\n# on initial setup in the `load()` method.\n#\n\nclass SpotMarketInstructionBuilder(MarketInstructionBuilder):\n def __init__(self, context: Context, wallet: Wallet, group: Group, account: Account, spot_market: SpotMarket, raw_market: PySerumMarket, market_index: int, fee_discount_token_address: typing.Optional[PublicKey]):\n super().__init__()\n self.context: Context = context\n self.wallet: Wallet = wallet\n self.group: Group = group\n self.account: Account = account\n self.spot_market: SpotMarket = spot_market\n self.raw_market: PySerumMarket = raw_market\n self.market_index: int = market_index\n self.fee_discount_token_address: typing.Optional[PublicKey] = fee_discount_token_address\n\n self.open_orders_address: typing.Optional[PublicKey] = self.account.spot_open_orders[self.market_index]\n\n @staticmethod\n def load(context: Context, wallet: Wallet, group: Group, account: Account, spot_market: SpotMarket) -> \"SpotMarketInstructionBuilder\":\n raw_market: PySerumMarket = PySerumMarket.load(\n context.client.compatible_client, spot_market.address, context.serum_program_address)\n\n fee_discount_token_address: typing.Optional[PublicKey] = None\n srm_token = context.token_lookup.find_by_symbol(\"SRM\")\n if srm_token is not None:\n fee_discount_token_account = TokenAccount.fetch_largest_for_owner_and_token(\n context, wallet.address, srm_token)\n if fee_discount_token_account is not None:\n fee_discount_token_address = fee_discount_token_account.address\n\n market_index = group.find_spot_market_index(spot_market.address)\n\n return SpotMarketInstructionBuilder(context, wallet, group, account, spot_market, raw_market, market_index, fee_discount_token_address)\n\n def build_cancel_order_instructions(self, order: Order, ok_if_missing: bool = False) -> CombinableInstructions:\n if self.open_orders_address is None:\n return CombinableInstructions.empty()\n\n return build_cancel_spot_order_instructions(\n self.context, self.wallet, self.group, self.account, self.raw_market, order, self.open_orders_address)\n\n def build_place_order_instructions(self, order: Order) -> CombinableInstructions:\n return build_spot_place_order_instructions(self.context, self.wallet, self.group, self.account,\n self.raw_market, order.order_type, order.side, order.price,\n order.quantity, order.client_id,\n self.fee_discount_token_address)\n\n def build_settle_instructions(self) -> CombinableInstructions:\n if self.open_orders_address is None:\n return CombinableInstructions.empty()\n\n base_rootbank = self.group.find_token_info_by_token(self.spot_market.base).root_bank\n base_nodebank = base_rootbank.pick_node_bank(self.context)\n quote_rootbank = self.group.find_token_info_by_token(self.spot_market.quote).root_bank\n quote_nodebank = quote_rootbank.pick_node_bank(self.context)\n return build_spot_settle_instructions(self.context, self.wallet, self.account,\n self.raw_market, self.group, self.open_orders_address,\n base_rootbank, base_nodebank, quote_rootbank, quote_nodebank)\n\n def build_crank_instructions(self, open_orders_addresses: typing.Sequence[PublicKey], limit: Decimal = Decimal(32)) -> CombinableInstructions:\n if self.open_orders_address is None:\n return CombinableInstructions.empty()\n\n open_orders_to_crank: typing.Sequence[PublicKey] = [*open_orders_addresses, self.open_orders_address]\n distinct_open_orders_addresses: typing.List[PublicKey] = []\n for oo in open_orders_to_crank:\n if oo not in distinct_open_orders_addresses:\n distinct_open_orders_addresses += [oo]\n\n limited_open_orders_addresses = distinct_open_orders_addresses[0:min(\n int(limit), len(distinct_open_orders_addresses))]\n\n limited_open_orders_addresses.sort(key=encode_public_key_for_sorting)\n\n return build_serum_consume_events_instructions(self.context, self.spot_market.address, self.raw_market.state.event_queue(), limited_open_orders_addresses, int(limit))\n\n def build_redeem_instructions(self) -> CombinableInstructions:\n return CombinableInstructions.empty()\n\n def build_create_openorders_instructions(self) -> CombinableInstructions:\n return build_spot_openorders_instructions(self.context, self.wallet, self.group, self.account, self.raw_market)\n\n def __str__(self) -> str:\n return f\"« 𝚂𝚙𝚘𝚝𝙼𝚊𝚛𝚔𝚎𝚝𝙸𝚗𝚜𝚝𝚛𝚞𝚌𝚝𝚒𝚘𝚗𝙱𝚞𝚒𝚕𝚍𝚎𝚛 [{self.spot_market.symbol}] »\"\n","sub_path":"mango/spotmarketinstructionbuilder.py","file_name":"spotmarketinstructionbuilder.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"19928885","text":"import asyncio\nfrom typing import List, Callable, Awaitable, Union\n\nimport discord\nfrom discord import Message, Embed, Emoji\nfrom discord.ext.commands import Context\n\nAnyEmoji = Union[str, Emoji]\n\n\nasync def run_tabbed_message(ctx: Context, emojis: List[AnyEmoji], embeds: List[Embed], files=None, starting_index=0,\n timeout=600):\n if len(emojis) != len(embeds):\n raise ValueError('Emojis and embeds must have the same number of elements.')\n\n message = await ctx.send(files=files, embed=embeds[starting_index])\n\n async def callback(emoji):\n await message.edit(embed=embeds[emojis.index(emoji)])\n\n await run_reaction_message(ctx, message, emojis, callback, timeout)\n\n\nasync def run_dynamically_paged_message(ctx: Context, embed_generator: Callable[[int], discord.Embed], timeout=600):\n left_arrow = '◀'\n right_arrow = '▶'\n arrows = [left_arrow, right_arrow]\n\n message = await ctx.send(embed=embed_generator(0))\n\n async def callback(emoji):\n if emoji == left_arrow:\n new_embed = embed_generator(-1)\n elif emoji == right_arrow:\n new_embed = embed_generator(1)\n else:\n return\n\n if new_embed:\n await message.edit(embed=new_embed)\n\n await run_reaction_message(ctx, message, arrows, callback, timeout)\n\n\nasync def run_paged_message(ctx: Context, base_embed: discord.Embed, content: List[str], page_size: int = 15,\n header='', numbered: bool = True, timeout=600, max_tabbed_pages=4, files=None):\n if header:\n header = f'`{header}`\\n'\n\n if max_tabbed_pages > 9:\n raise ValueError('max_tabbed_pages must be 9 or less.')\n\n if not content:\n embed = base_embed.copy().set_footer(text='Page 0/0')\n message = await ctx.send(embed=embed)\n await run_deletable_message(ctx, message, timeout)\n return\n\n page_contents = [content[i:i + page_size] for i in range(0, len(content), page_size)]\n\n item_number = 0\n max_item_number_length = len(str(len(content)))\n\n def format_item(item):\n nonlocal item_number\n item_number += 1\n if numbered:\n return f'`{item_number}.{\" \" * (max_item_number_length - len(str(item_number)))} {item}`'\n else:\n return f'`{item}`'\n\n embeds = [\n base_embed.from_dict({\n **base_embed.to_dict(),\n 'description': header + '\\n'.join((format_item(i) for i in page)),\n }).set_footer(text=f'Page {i + 1}/{len(page_contents)}')\n for i, page in enumerate(page_contents)]\n\n if len(embeds) == 1:\n message = await ctx.send(embed=embeds[0])\n await run_deletable_message(ctx, message, timeout)\n return\n\n if len(embeds) <= max_tabbed_pages:\n reaction_emoji = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣']\n await run_tabbed_message(ctx, reaction_emoji[:len(embeds)], embeds, timeout=timeout)\n else:\n message = await ctx.send(embed=embeds[0], files=files or [])\n\n double_left_arrow = '⏪'\n double_right_arrow = '⏩'\n left_arrow = '◀'\n right_arrow = '▶'\n\n arrows = [double_left_arrow, left_arrow, right_arrow, double_right_arrow]\n\n index = 0\n\n async def callback(emoji):\n nonlocal index\n start_index = index\n if emoji == double_left_arrow:\n index = 0\n elif emoji == left_arrow:\n index -= 1\n elif emoji == right_arrow:\n index += 1\n elif emoji == double_right_arrow:\n index = len(embeds) - 1\n index = min(len(embeds) - 1, max(0, index))\n\n if index != start_index:\n await message.edit(embed=embeds[index])\n\n await run_reaction_message(ctx, message, arrows, callback, timeout)\n\n\nasync def run_deletable_message(ctx: Context, message: Message, timeout=600):\n await run_reaction_message(ctx, message, [], _noop, timeout=timeout)\n\n\nasync def _noop(n):\n return None\n\n\nasync def run_reaction_message(ctx: Context, message: Message, emojis: List[AnyEmoji],\n callback: Callable[[AnyEmoji], Awaitable[None]], timeout=600):\n emojis.append('❎')\n for emoji in emojis:\n await message.add_reaction(emoji)\n\n def check(rxn, usr):\n return usr == ctx.author and rxn.emoji in emojis and rxn.message.id == message.id\n\n while True:\n try:\n reaction, user = await ctx.bot.wait_for('reaction_add', timeout=timeout, check=check)\n if reaction.emoji == '❎':\n await message.delete()\n return\n await callback(reaction.emoji)\n await message.remove_reaction(reaction, user)\n except asyncio.TimeoutError:\n for emoji in emojis:\n await message.remove_reaction(emoji, ctx.bot.user)\n break\n","sub_path":"miyu_bot/commands/common/reaction_message.py","file_name":"reaction_message.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"212752232","text":"import json\nimport pika\n\nfrom send_email import enviar_email\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters('localhost')\n)\n\nchannel = connection.channel()\n\nchannel.queue_declare(queue=\"send_email\")\n\n\ndef email(ch, method, properties, body):\n data = json.loads(str(body)[2:-1])\n enviar_email(data['subject'], data['to'], data['from_email'], data['body'])\n\n\nchannel.basic_consume(email, queue='send_email', no_ack=True)\n\nprint(\"Inicio worker\")\n\nchannel.start_consuming()","sub_path":"rabbit_email/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"325604149","text":"\"\"\"\nCommands for publishing particle cloud and pose estimate updates.\n\"\"\"\n\n# pyright: reportMissingTypeStubs=false\n\nfrom typing import Any, List\n\nfrom geometry_msgs.msg import PoseArray, PoseStamped\nimport rospy\nfrom rospy_util.controller import Cmd\nfrom std_msgs.msg import Header\n\nfrom lib.particle import Particle\nimport lib.turtle_pose as tp\nfrom lib.turtle_pose import TurtlePose\n\n\ndef update_estimated_robot_pose(pose: TurtlePose, frame_id: str) -> Cmd[PoseStamped]:\n \"\"\"\n Update the estimated robot pose.\n \"\"\"\n header = mk_header(frame_id)\n pose_stamped = PoseStamped(header, tp.to_pose(pose))\n\n return Cmd(\n topic_name=\"/estimated_robot_pose\",\n message_type=PoseStamped,\n message_value=pose_stamped,\n )\n\n\ndef update_particle_cloud(particles: List[Particle], frame_id: str) -> Cmd[PoseArray]:\n \"\"\"\n Update the particle cloud after each iteration of the particle filter.\n \"\"\"\n return publish_particle_cloud(particles, frame_id, latch=False)\n\n\ndef init_particle_cloud(particles: List[Particle], frame_id: str) -> Cmd[PoseArray]:\n \"\"\"\n Publish the the particle cloud after initialization.\n \"\"\"\n return publish_particle_cloud(particles, frame_id, latch=True)\n\n\ndef publish_particle_cloud(\n particles: List[Particle],\n frame_id: str,\n latch: bool,\n) -> Cmd[PoseArray]:\n \"\"\"\n Publish the particle cloud, optionally latching to ensure the message is\n received by new subscribers.\n \"\"\"\n pose_array = pose_array_from_particles(particles, frame_id)\n\n return Cmd(\n topic_name=\"/particle_cloud\",\n message_type=PoseArray,\n message_value=pose_array,\n latch_publisher=latch,\n )\n\n\n\"\"\"\nThe no-op command (an empty list of commands).\n\"\"\"\nnone: List[Cmd[Any]] = []\n\n\ndef pose_array_from_particles(particles: List[Particle], frame_id: str) -> PoseArray:\n \"\"\"\n Create a PoseArray message from the particle cloud.\n \"\"\"\n header = mk_header(frame_id)\n poses = [tp.to_pose(p.pose) for p in particles]\n return PoseArray(header, poses)\n\n\ndef mk_header(frame_id: str) -> Header:\n \"\"\"\n Create a ROS message header for the current time and specified frame.\n \"\"\"\n return Header(stamp=rospy.Time.now(), frame_id=frame_id)\n","sub_path":"scripts/lib/controller/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"276926122","text":"# -*- coding: utf-8 -*-\nfrom plone import api\nfrom plone.app.upgrade.utils import loadMigrationProfile\nfrom Products.CMFCore.utils import getToolByName\nfrom zope.container.interfaces import INameChooser\nfrom zope.component import getUtility\nfrom zope.component import getMultiAdapter\n\nfrom plone.portlets.interfaces import IPortletManager\nfrom plone.portlets.interfaces import IPortletAssignmentMapping\n\nfrom emc.project.content.projectfolder import IProjectFolder\nfrom emc.policy.portlets import navigation\n\ndef setupGroups(context):\n\n# import pdb\n# pdb.set_trace()\n group = api.group.create(\n groupname='System Administrators',\n title='System Administrators',\n description='EMC System Administrators',\n roles=['SysAdmin','Site Administrator', ],\n ) \n group = api.group.create(\n groupname='Secure Staffs',\n title='Secure Staffs',\n description='EMC Secure Staffs',\n roles=['SecStaff','Site Administrator', ],\n ) \n group = api.group.create(\n groupname='Secure Auditors',\n title='Secure Auditors',\n description='EMC Secure Auditors',\n roles=['SecAuditor','Site Administrator', ],\n )\n# for i in range(1,3): \n# api.user.create(\n# username='master%s' % i,\n# email='master%s@plone.org' % i,\n# password='secret$',\n# ) \n api.group.add_user(groupname='System Administrators', username='test17')\n api.group.add_user(groupname='Secure Staffs', username='test18')\n api.group.add_user(groupname='Secure Auditors', username='test19')\n\ndef add_navigator_portlet(context):\n pc = getToolByName(context, \"portal_catalog\")\n query = {\"object_provides\":IProjectFolder.__identifier__}\n bns = pc(query)\n if len(bns) == 0: return\n obj = bns[0].getObject()\n# column = getUtility(IPortletManager, name=u\"plone.leftcolumn\")\n column = getUtility(IPortletManager, name=u\"plone.rightcolumn\")\n \n # We multi-adapt the object and the column to an assignment mapping,\n # which acts like a dict where we can put portlet assignments\n manager = getMultiAdapter((obj, column,), IPortletAssignmentMapping)\n \n # We then create the assignment and put it in the assignment manager,\n # using the default name-chooser to pick a suitable name for us.\n assignment = navigation.Assignment(name=u\"项目管理\",root_uid=obj.UID(),topLevel=0)\n chooser = INameChooser(manager)\n manager[chooser.chooseName(None, assignment)] = assignment\n\ndef add_member_navigator_portlet(context):\n pc = getToolByName(context, \"portal_catalog\")\n query = {\"object_provides\":IProjectFolder.__identifier__,\"id\":\"Members\"}\n bns = pc(query)\n if len(bns) == 0: return\n obj = bns[0].getObject()\n # column = getUtility(IPortletManager, name=u\"plone.leftcolumn\")\n column = getUtility(IPortletManager, name=u\"plone.rightcolumn\")\n # We multi-adapt the object and the column to an assignment mapping,\n # which acts like a dict where we can put portlet assignments\n manager = getMultiAdapter((obj, column,), IPortletAssignmentMapping)\n \n # We then create the assignment and put it in the assignment manager,\n # using the default name-chooser to pick a suitable name for us.\n assignment = navigation.Assignment(name=u\"工作空间\",root_uid=obj.UID(),topLevel=0)\n chooser = INameChooser(manager)\n manager[chooser.chooseName(None, assignment)] = assignment\n\n# loadMigrationProfile(context, 'profile-emc.policy:to507')\n \n \n\n\n","sub_path":"emc/policy/migration.py","file_name":"migration.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"92494329","text":"#!/usr/bin/env python\n#\n# copyoverlay.py - Action which copies the currently selected overlay.\n#\n# Author: Paul McCarthy \n#\n\"\"\"This module provides the :class:`CopyOverlayAction`, a global action\nwhich creates a copy of the currently selected overlay.\n\"\"\"\n\n\nimport numpy as np\n\nimport fsl.data.image as fslimage\nimport fsl.utils.transform as transform\nimport fsl.utils.settings as fslsettings\nimport fsleyes_widgets.dialog as fsldlg\nimport fsleyes.strings as strings\nfrom . import base\n\n\nclass CopyOverlayAction(base.Action):\n \"\"\"The ``CopyOverlayAction`` does as its name suggests - it creates a\n copy of the currently selected overlay.\n\n\n .. note:: Currently this action is only capable of copying ``.Image``\n overlays.\n\n\n The user is asked to choose between the following options:\n\n - If the overlay is a 4D ``Image``, should we copy the entire 4D image,\n or extract the current 3D volume?\n\n - Should we copy all of the ``Image`` data, or create a blank\n (i.e. filled with zeros) ``Image`` of the same dimensions?\n\n - Should we copy the ``Image`` display properties\n (e.g. :attr:`.Display.overlayType`), or set the display properties\n of the copy to defaults?\n \"\"\"\n\n\n def __init__(self, overlayList, displayCtx, frame):\n \"\"\"Create a ``CopyOverlayAction``.\n\n :arg overlayList: The :class:`.OverlayList`.\n :arg displayCtx: The :class:`.DisplayContext`.\n :arg frame: The :class:`.FSLeyesFrame`.\n \"\"\"\n base.Action.__init__(self, self.__copyOverlay)\n\n self.__overlayList = overlayList\n self.__displayCtx = displayCtx\n self.__frame = frame\n self.__name = '{}_{}'.format(type(self).__name__, id(self))\n\n displayCtx .addListener('selectedOverlay',\n self.__name,\n self.__selectedOverlayChanged)\n overlayList.addListener('overlays',\n self.__name,\n self.__selectedOverlayChanged)\n\n self.__selectedOverlayChanged()\n\n\n def destroy(self):\n \"\"\"Removes listeners from the :class:`.DisplayContext` and\n :class:`.OverlayList`, and calls :meth:`.Action.destroy`.\n \"\"\"\n\n self.__displayCtx .removeListener('selectedOverlay', self.__name)\n self.__overlayList.removeListener('overlays', self.__name)\n base.Action.destroy(self)\n\n\n def __selectedOverlayChanged(self, *a):\n \"\"\"Called when the selected overlay, or overlay list, changes.\n\n Enables/disables this action depending on the nature of the selected\n overlay.\n \"\"\"\n\n ovl = self.__displayCtx.getSelectedOverlay()\n self.enabled = (ovl is not None) and isinstance(ovl, fslimage.Image)\n\n\n def __copyOverlay(self):\n \"\"\"Creates a copy of the currently selected overlay, and inserts it\n into the :class:`.OverlayList`.\n \"\"\"\n\n import wx\n\n overlay = self.__displayCtx.getSelectedOverlay()\n\n if overlay is None:\n return\n\n # TODO support for other overlay types\n if type(overlay) != fslimage.Image:\n raise RuntimeError('Currently, only {} instances can be '\n 'copied'.format(fslimage.Image.__name__))\n\n display = self.__displayCtx.getDisplay(overlay)\n\n # We ask the user questions three:\n # - Copy data, or create an empty (a.k.a. mask) image?\n # - Copy display settings?\n # - For 4D, copy 4D, or just the current 3D volume?\n #\n # Here we build a list of\n # questions and initial states.\n options = []\n states = []\n\n createMaskSetting = 'fsleyes.actions.copyoverlay.createMask'\n copyDisplaySetting = 'fsleyes.actions.copyoverlay.copyDisplay'\n copy4DSetting = 'fsleyes.actions.copyoverlay.copy4D'\n\n createMask = fslsettings.read(createMaskSetting, False)\n copyDisplay = fslsettings.read(copyDisplaySetting, False)\n copy4D = fslsettings.read(copy4DSetting, False)\n is4D = len(overlay.shape) > 3 and overlay.shape[3] > 1\n\n options.append(strings.messages['actions.copyoverlay.createMask'])\n states .append(createMask)\n\n options.append(strings.messages['actions.copyoverlay.copyDisplay'])\n states .append(copyDisplay)\n\n if is4D:\n options.append(strings.messages['actions.copyoverlay.copy4D'])\n states .append(copy4D)\n\n # Ask the user what they want to do\n dlg = fsldlg.CheckBoxMessageDialog(\n self.__frame,\n title=strings.actions[self],\n message='Copy {}'.format(display.name),\n cbMessages=options,\n cbStates=states,\n yesText='OK',\n cancelText='Cancel',\n focus='yes')\n\n if dlg.ShowModal() != wx.ID_YES:\n return\n\n createMask = dlg.CheckBoxState(0)\n copyDisplay = dlg.CheckBoxState(1)\n if is4D:\n copy4D = dlg.CheckBoxState(2)\n\n fslsettings.write(createMaskSetting, createMask)\n fslsettings.write(copyDisplaySetting, copyDisplay)\n if is4D:\n fslsettings.write(copy4DSetting, copy4D)\n\n copyImage(self.__overlayList,\n self.__displayCtx,\n overlay,\n createMask=createMask,\n copy4D=copy4D,\n copyDisplay=copyDisplay)\n\n\ndef copyImage(overlayList,\n displayCtx,\n overlay,\n createMask=False,\n copy4D=True,\n copyDisplay=True,\n name=None,\n roi=None,\n data=None):\n \"\"\"Creates a copy of the given :class:`.Image` overlay, and inserts it\n into the :class:`.OverlayList`.\n\n :arg overlayList: The :class:`.OverlayList`.\n\n :arg displayCtx: The :class:`.DisplayContext`.\n\n :arg overlay: The :class:`.Image` to be copied.\n\n :arg createMask: If ``True``, the copy will be an empty ``Image`` the\n same shape as the ``overlay``.\n\n :arg copy4D: If ``True``, and the ``overlay`` is 4D, the copy will\n also be 4D. Otherwise, the current 3D voluem is copied.\n\n :arg copyDisplay: If ``True``, the copy will inherit the display settings\n of the ``overlay``. Otherwise, the copy will be\n initialised with default display settings.\n\n :arg name: If provided, will be used as the :attr:`.Display.name`\n of the copy. Otherwise the copy will be given a name.\n\n :arg roi: If provided, the copy will be cropped to the low/high\n voxel bounds specified in the image. Must be a sequence\n of tuples, containing the low/high bounds for each voxel\n dimension. For 4D images, the bounds for the fourth\n dimension are optional.\n\n :arg data: If provided, is used as the image data for the new copy.\n Must match the shape dictated by the other arguments\n (i.e. ``copy4D`` and ``roi``). If ``data`` is provided,\n the ``createMask`` argument is ignored.\n\n :returns: The newly created :class:`.Image` object.\n \"\"\"\n\n ovlIdx = overlayList.index(overlay)\n opts = displayCtx.getOpts(overlay)\n isROI = roi is not None\n is4D = len(overlay.shape) > 3 and overlay.shape[3] > 1\n\n if name is None:\n name = '{}_copy'.format(overlay.name)\n\n if roi is None:\n roi = [(0, s) for s in overlay.shape]\n\n # If the image is 4D, and an ROI of\n # length 3 has been given, add some\n # bounds for the fourth dimension\n if is4D and copy4D and len(roi) == 3:\n roi = list(roi) + [(0, overlay.shape[3])]\n\n # If we are only supposed to copy\n # the current 3D volume of a 4D\n # image, adjust the ROI accordingly.\n if is4D and not copy4D:\n roi = list(roi[:3]) + [(opts.volume, opts.volume + 1)]\n\n shape = [hi - lo for lo, hi in roi]\n slc = tuple([slice(lo, hi) for lo, hi in roi])\n\n if data is not None: pass\n elif createMask: data = np.zeros(shape)\n else: data = np.copy(overlay[slc])\n\n # If this is an ROI, we need to add\n # an offset to the image affine\n if isROI:\n xform = overlay.voxToWorldMat\n offset = [lo for lo, hi in roi[:3]]\n offset = transform.scaleOffsetXform([1, 1, 1], offset)\n xform = transform.concat(xform, offset)\n\n else:\n xform = None\n\n # Create the copy, put it in the list\n header = overlay.header.copy()\n copy = fslimage.Image(data, name=name, header=header, xform=xform)\n\n overlayList.insert(ovlIdx + 1, copy)\n\n # Copy the Display/DisplayOpts settings\n if copyDisplay:\n\n srcDisplay = displayCtx.getDisplay(overlay)\n destDisplay = displayCtx.getDisplay(copy)\n\n for prop in srcDisplay.getAllProperties()[0]:\n\n # Don't override the name\n # that we set above\n if prop == 'name':\n continue\n\n val = getattr(srcDisplay, prop)\n setattr(destDisplay, prop, val)\n\n # And after the Display has been configured\n # copy the DisplayOpts settings.\n srcOpts = displayCtx.getOpts(overlay)\n destOpts = displayCtx.getOpts(copy)\n\n for prop in srcOpts.getAllProperties()[0]:\n\n # But don't clobber the transform, and related,\n # properties, as it is (typically) automatically\n # controlled via the DisplayContext.displaySpace\n if prop in ('transform', 'bounds'):\n continue\n\n val = getattr(srcOpts, prop)\n setattr(destOpts, prop, val)\n\n return copy\n","sub_path":"fsleyes/actions/copyoverlay.py","file_name":"copyoverlay.py","file_ext":"py","file_size_in_byte":10000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"43519583","text":"'''\r\nGoogle Code Jam 2016\r\nRound 1C\r\nProblem A - Senate Evacuation\r\n'''\r\n\r\ncases = int(raw_input())\r\n\r\nfor case in range (cases):\r\n\tn = int(raw_input())\r\n\tp = raw_input().split(\" \")\r\n\talphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n\t# find total senate members\r\n\ttotal = 0\r\n\tfor i in range (n):\r\n\t\ttotal = total + int(p[i])\r\n\t\tp[i] = [int(p[i]), alphabet[i]]\r\n\tp.sort(reverse = True)\r\n\t\r\n\ty = \"\"\r\n\twhile total > 0:\r\n\t\tcount = 0\r\n\t\tfor i in range (n):\r\n\t\t\tif p[i][0] == p[0][0]:\r\n\t\t\t\tcount = count + 1\r\n\t\tif count == len(p) and len(p) > 2:\r\n\t\t\ty = y + p[0][1] + \" \"\r\n\t\t\tp[0][0] = p[0][0] - 1\r\n\t\t\ttotal = total - 1\r\n\t\t\tp.sort(reverse = True)\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\ty = y + p[0][1]\r\n\t\t\tp[0][0] = p[0][0] - 1\r\n\t\t\ttotal = total - 1\r\n\t\t\tif p[1][0] < total / 2:\r\n\t\t\t\ty = y + p[0][1] + \" \"\r\n\t\t\t\tp[0][0] = p[0][0] - 1\r\n\t\t\t\ttotal = total - 1\r\n\t\t\telse:\r\n\t\t\t\ty = y + p[1][1] + \" \"\r\n\t\t\t\tp[1][0] = p[1][0] - 1\r\n\t\t\t\ttotal = total - 1\r\n\t\t\tp.sort(reverse = True)\r\n\t\r\n\tprint (\"Case #{}: {}\".format(case + 1, y))","sub_path":"codes/CodeJamCrawler/16_3_1_neat/16_3_1_ronaudinho_A.py","file_name":"16_3_1_ronaudinho_A.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"430159334","text":"\n'''\nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import fft\nfrom scipy.io import wavfile # get the api\nfs, data = wavfile.read('Amogh.wav') # load the data\n\ndata0 = data[:0]\nprint(data0)\n\na = data.T[0] # this is a two channel soundtrack, I get the first track\nb=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1)\nc = fft(b) # calculate fourier transform (complex numbers list)\nd = len(c)/2 # you only need half of the fft list (real signal symmetry)\nplt.plot(abs(c[:(d-1)]),'r') \nplt.show()\n'''\nimport wave, struct\n\nwavefile = wave.open('Amogh.wav', 'r')\n\nlength = wavefile.getnframes()\nfor i in range(0, length):\n wavedata = wavefile.readframes(13)\n data = struct.unpack(\"<13h\", wavedata)\n print(int(data[0]))\n\n","sub_path":"Sonic Auth/Data Transfer/sssa.py","file_name":"sssa.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"301706741","text":"# myAgentP3.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n# This file was based on the starter code for student bots, and refined \n# by Mesut (Xiaocheng) Yang\n\n\nfrom captureAgents import CaptureAgent\nimport random, time, util\nfrom game import Directions\nimport game\nfrom util import nearestPoint\n\n#########\n# Agent #\n#########\nclass MyAgent(CaptureAgent):\n \"\"\"\n YOUR DESCRIPTION HERE\n \"\"\"\n\n def registerInitialState(self, gameState):\n \"\"\"\n This method handles the initial setup of the\n agent to populate useful fields (such as what team\n we're on).\n\n A distanceCalculator instance caches the maze distances\n between each pair of positions, so your agents can use:\n self.distancer.getDistance(p1, p2)\n\n IMPORTANT: This method may run for at most 15 seconds.\n \"\"\"\n\n # Make sure you do not delete the following line. \n # If you would like to use Manhattan distances instead \n # of maze distances in order to save on initialization \n # time, please take a look at:\n # CaptureAgent.registerInitialState in captureAgents.py.\n CaptureAgent.registerInitialState(self, gameState)\n self.start = gameState.getAgentPosition(self.index)\n\n def chooseAction(self, gameState):\n \"\"\"\n Picks among actions randomly.\n \"\"\"\n teammateActions = self.receivedBroadcast\n # Process your teammate's broadcast! \n # Use it to pick a better action for yourself\n\n actions = gameState.getLegalActions(self.index)\n\n filteredActions = actionsWithoutReverse(actionsWithoutStop(actions), gameState, self.index)\n\n currentAction = random.choice(actions) # Change this!\n return currentAction\n\ndef actionsWithoutStop(legalActions):\n \"\"\"\n Filters actions by removing the STOP action\n \"\"\"\n legalActions = list(legalActions)\n if Directions.STOP in legalActions:\n legalActions.remove(Directions.STOP)\n return legalActions\n\ndef actionsWithoutReverse(legalActions, gameState, agentIndex):\n \"\"\"\n Filters actions by removing REVERSE, i.e. the opposite action to the previous one\n \"\"\"\n legalActions = list(legalActions)\n reverse = Directions.REVERSE[gameState.getAgentState(agentIndex).configuration.direction]\n if len (legalActions) > 1 and reverse in legalActions:\n legalActions.remove(reverse)\n return legalActions\n","sub_path":"PacPack_Spring_2019/myAgent.py","file_name":"myAgent.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"60290397","text":"gbif_base_url = 'http://api.gbif.org/v1/species'\n\ndef gbif_name_backbone(name, rank = None, kingdom = None, phylum = None,\n clazz = None, order = None, family = None, genus = None, strict = False,\n start = None, limit = 500, **kwargs):\n\n url = gbif_base_url + '/match'\n args = {'name': name, 'rank': rank, 'kingdom': kingdom,\n 'phylum': phylum, 'class': clazz, 'order': order, 'family': family,\n 'genus': genus, 'strict': strict, 'verbose': True, 'offset': start,\n 'limit': limit}\n return Refactor(url, payload=args, request='get').json()\n\ndef gbif_name_lookup(query = None, rank = None, higherTaxonKey = None, status = None,\n nameType = None, datasetKey = 'd7dddbf4-2cf0-4f39-9b2a-bb099caae36c',\n limit = 500, start = None, **kwargs):\n\n url = gbif_base_url + '/search'\n args = {'q': query, 'rank': rank, 'higherTaxonKey': higherTaxonKey,\n 'status': status, 'nameType': nameType, 'datasetKey': datasetKey,\n 'limit': limit, 'offset': start}\n return Refactor(url, payload=args, request='get').json()\n","sub_path":"pytaxize/gbif_utils.py","file_name":"gbif_utils.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"286994390","text":"import pytest\nimport SPL.driver.driver_factory as p_driver_factory\n\nfrom MobileApps.libs.flows.ios.smart.flow_container import FlowContainer\nfrom MobileApps.resources.const.ios.const import *\n\npytest.app_info = \"SMART\"\n\nclass Test_suite_01_ios_smart_scan_from_camera_ga(object):\n\n @pytest.fixture(scope=\"class\", autouse=\"true\")\n def class_setup(cls, session_setup, load_printers_session):\n\n cls = cls.__class__\n\n cls.driver = session_setup\n cls.fc = FlowContainer(cls.driver)\n\n # Initializing Printer\n cls.sys_config = ma_misc.load_system_config_file()\n cls.p = load_printers_session\n # cls.printer_ip = cls.p.p_obj.ipAddress\n cls.printer_info = cls.p.get_printer_information()\n\n # Printer variables\n cls.printer_ip = cls.printer_info['ip address']\n\n cls.fc.go_home(verify_ga=True)\n\n def test_01_scan_by_camera_max_ga(self):\n\n\n self.fc.add_printer_by_ip(printer_ip=self.printer_ip)\n self.fc.go_camera_screen_from_home()\n self.fc.fd[\"camera\"].capture_manual_photo_by_camera()\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"scan_edit\"].select_scan_editing_for_rotate_and_crop(SCAN_EDIT_ROTATE.LEFT, SCAN_EDIT_CROP.A4)\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"preview\"].handle_share_preview_screen()\n self.fc.fd[\"preview\"].select_file_converting_format(PREVIEW_FILE_TYPE.PDF)\n self.fc.fd[\"preview\"].select_save()\n # Clean up Steps\n self.fc.fd[\"scan\"].select_back()\n self.fc.fd[\"scan\"].verify_preview_navigate_back_popup()\n self.fc.fd[\"preview\"].select_yes_btn()\n\n def test_02_scan_by_camera_print_edit_max_ga(self):\n\n self.fc.go_camera_screen_from_home()\n self.fc.fd[\"camera\"].capture_manual_photo_by_camera()\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"preview\"].select_add_page()\n self.fc.fd[\"camera\"].verify_camera_screen()\n self.fc.fd[\"camera\"].capture_manual_photo_by_camera()\n self.fc.fd[\"preview\"].verify_preview_screen()\n self.fc.fd[\"print_edit\"].select_print_edit_options_for_ga(re_size=PRINT_EDIT_RESIZE_AND_MOVE.MANUAL)","sub_path":"MobileApps/tests/ios/smart/ga/camera/test_suite_01_ios_smart_scan_from_camera_ga.py","file_name":"test_suite_01_ios_smart_scan_from_camera_ga.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"506234371","text":"from rest_framework import serializers\n\nfrom dataprocessing.serializers import userProfileSerializer\nfrom workprogramsapp.folders_ans_statistic.models import Folder, WorkProgramInFolder\nfrom workprogramsapp.serializers import WorkProgramShortForExperiseSerializer\n\n\nclass WorkProgramInFolderSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkProgramInFolder\n fields = \"__all__\"\n\n def to_representation(self, value):\n self.fields['work_program'] = WorkProgramShortForExperiseSerializer(many=False)\n return super().to_representation(value)\n\n\nclass FolderCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Folder\n fields = [\"id\", \"name\", \"description\"]\n\n\nclass FolderSerializer(serializers.ModelSerializer):\n class Meta:\n model = Folder\n fields = [\"id\", \"name\", \"description\", \"owner\", 'work_program_in_folder']\n\n def update(self, instance, validated_data):\n print(validated_data)\n # ... logic to save ingredients for this recipe instance\n return instance\n\n def to_representation(self, value):\n self.fields['owner'] = userProfileSerializer(many=False)\n #self.fields['work_program'] = WorkProgramShortForExperiseSerializer(many=True)\n self.fields['work_program_in_folder'] = WorkProgramInFolderSerializer(many=True)\n return super().to_representation(value)\n","sub_path":"application/workprogramsapp/folders_ans_statistic/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"200964797","text":"import bpy\r\nn='dp'\r\ndef a(ob):\r\n s=bpy.context.scene\r\n bpy.ops.object.select_all(action='DESELECT')\r\n ob.select=True\r\n s.objects.active=ob\r\n \r\nobs=bpy.context.selected_objects\r\ns=bpy.context.scene\r\n\r\nfor ob in obs:\r\n s.cursor_location=ob.matrix_world.translation\r\n a(ob)\r\n d=max(ob.dimensions.x,ob.dimensions.y,ob.dimensions.z)\r\n #bpy.ops.object.editmode_toggle()\r\n #bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=3, size=d/2, view_align=False, enter_editmode=False)\r\n #bpy.ops.mesh.select_all(action='INVERT')\r\n #bpy.ops.mesh.delete(type='VERT')\r\n\r\n #bpy.ops.object.editmode_toggle()\r\n #\r\n #bpy.ops.object.shade_smooth()\r\n bpy.ops.object.metaball_add(type='BALL', view_align=False, enter_editmode=False)\r\n bpy.context.object.name = n\r\n \r\n m=bpy.context.active_object\r\n m.scale*=ob.dimensions.z*.6\r\n m.data.resolution=0.2\r\nbpy.ops.object.editmode_toggle()\r\nbpy.ops.object.editmode_toggle()\r\n\r\n","sub_path":"presets/macros/metabolize.py","file_name":"metabolize.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"1814144","text":"from django.db import models\nfrom django.utils import timezone\n\nclass Tweeeet(models.Model):\n author = models.ForeignKey('auth.User', on_delete=models.CASCADE)\n text = models.CharField(max_length=280)\n tweeeted_date = models.DateTimeField(\n default = timezone.now)\n\n def tweeet(self):\n self.tweeeted_date = timezone.now()\n self.save()\n\n","sub_path":"twiitter/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"334242436","text":"import webapp2\nfrom models import *\nfrom google.appengine.api import users\nimport main\n\n\nclass LoginScreenHandler(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n\n if user:\n user_profile = Profile.query(Profile.user_key == user.user_id()).get()\n if user_profile is not None:\n self.redirect(\"/\")\n\n template_values = {'profile': None}\n template = main.jinja.get_template('pages/profile/login.html')\n self.response.write(template.render(template_values))","sub_path":"pages/profile/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"102544923","text":"__author__ = 'Keith Colbert'\n\n# A simple game to demonstrate use of sourceprotector to detect cheating\n\n\nimport time\nimport examplesourceprotector\n\n\nname = input('Enter your name: ')\n\nstart = time.time()\n\ninput('Quick, press enter!')\n\nend = time.time()\n\nelapsed = end - start\n\nscore = int(100 / elapsed)\n\nexamplesourceprotector.savescore(score)","sub_path":"Examples/highscores/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"302572734","text":"\n\nfrom collections import defaultdict, deque\nimport csv\n\n\n\n\ndef load_data(file_path):\n\tgraph, hero_to_id, id_to_hero = defaultdict(set), {}, {}\n\n\tdef get_or_set_id(key):\n\t\tif key not in hero_to_id:\n\t\t\tid = get_or_set_id._max_id = get_or_set_id._max_id +1\n\t\t\thero_to_id[key], id_to_hero[id] = id, key\n\t\treturn hero_to_id[key]\n\n\tget_or_set_id._max_id = 0\n\n\tcsv_reader = csv.reader(open(file_path, 'rb'), delimiter='\\t')\n\tfor hero, comic in csv_reader:\n\t\thero_id = get_or_set_id(hero)\n\t\tgraph[hero_id].add(comic)\n\t\tgraph[comic].add(hero_id)\n\n\treturn (graph, id_to_hero, hero_to_id)\n\n\ndef update_edge(graph, one, two):\n\tgraph[one][two] = graph[one].get(two, 0) + 1\n\tgraph[two][one] = graph[two].get(one, 0) + 1\n\n\ndef build_edges(graph, id_to_hero):\n\tresult = defaultdict(dict)\n\n\tfor hero in id_to_hero:\n\t\tfor comic in graph[hero]:\n\t\t\tfor other_hero in graph[comic]:\n\t\t\t\tif other_hero < hero:\n\t\t\t\t\tupdate_edge(result, hero, other_hero)\n\n\tfor one in result:\n\t\tfor two in result[one]:\n\t\t\tresult[one][two] = 1.0 / result[one][two]\n\treturn result\n\n\n\ndef find_hop_path(graph, start, goal):\n\tfrontier, explored = deque([[start]]), set()\n\n\twhile frontier:\n\t\tcurrent_path = frontier.popleft()\n\t\tlast_node = current_path[-1]\n\t\texplored.add(last_node)\n\n\t\tfor successor in graph[last_node]:\n\t\t\tif successor not in explored:\n\t\t\t\tif successor == goal: return current_path + [successor]\n\t\t\t\tfrontier.append(current_path + [successor])\n\n\n\ndef find_weighted_path(graph, start, goal):\n\treturn []\n\n\n\n\ndef main():\n\tfile_path = 'marvel.tsv'\n\tgraph, id_to_hero, hero_to_id = load_data(file_path)\n\tgraph = build_edges(graph, id_to_hero)\n\n\tmain_heroes = ('SPIDER-MAN/PETER PAR',) #, 'GREEN GOBLIN/NORMAN ', 'WOLVERINE/LOGAN ', 'PROFESSOR X/CHARLES ', 'CAPTAIN AMERICA')\n\n\tresult = 0\n\n\tfor hero_name in main_heroes:\n\t\thero = hero_to_id[hero_name]\n\t\tfor other_hero in id_to_hero:\n\t\t\tif other_hero == hero: continue\n\n\t\t\thop_path = find_hop_path(graph, hero, other_hero)\n\t\t\tweighted_path = find_weighted_path(graph, hero, other_hero)\n\t\t\tif hop_path != weighted_path: result += 1\n\t\t\tprint('{}, {}: {}'.format(hero, other_hero, hop_path))\n\n\tprint(result)\n\n\n\n# def main():\n# \tfile_path = 'marvel.tsv'\n# \tgraph, id_to_hero = load_data(file_path)\n# \tedges = build_edges(graph, id_to_hero)\n# \tresult = map_hero_names(get_top_k_edges(edges, 4), id_to_hero)\n# \tprint(result)\n\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"Week5/Assignments/weighted_marvel__2.py","file_name":"weighted_marvel__2.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"137945108","text":"# Import the framework\nimport flask_api\nfrom flask import request\nfrom flask_api import status, exceptions\nimport pugsql\n\n# Import the dotenv to load variables from the environment\n# to run Flask using Foreman\nfrom dotenv import load_dotenv\nload_dotenv()\n\n# Create instance of Flask using the Flask API\napp = flask_api.FlaskAPI(__name__)\napp.config.from_envvar('APP_CONFIG')\n\nqueries = pugsql.module('queries/')\nqueries.connect(app.config['DATABASE_URL'])\n\n@app.cli.command('init')\ndef init_db():\n with app.app_context():\n db = queries._engine.raw_connection()\n with app.open_resource('entries.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n# Home page\n@app.route('/', methods=['GET'])\ndef home():\n #return 'Welcome to Nic\\'s localhost'\n return '''Welcome to Fake Reddit! '''\n\n# ---- Posting Microservice ----\n\n# List all entries\n@app.route('/api/v1/entries/all', methods=['GET'])\ndef all_entries():\n all_entries = queries.all_entries()\n return list(all_entries)\n\n# GET/DELETE given an id (also shows upvotes and downvotes)\n@app.route('/api/v1/entries/', methods=['GET','DELETE'])\ndef entry(id):\n if request.method == 'GET':\n return get_entry_with_id(id)\n elif request.method == 'DELETE':\n queries.delete_entry(id=id)\n return { 'message': f'Deleted post with id {id}' }, status.HTTP_200_OK\n\n# General GET/POST\n@app.route('/api/v1/entries', methods=['GET','POST'])\ndef entries():\n if request.method == 'GET':\n return filter_entries(request.args)\n elif request.method == 'POST':\n return create_entry(request.data)\n\n# GET n most recent entries, specific community\n@app.route('/api/v1/entries//recent/', methods=['GET'])\ndef get_community_recent(community, numOfEntries):\n community_entries = queries.entry_by_community(community=community, numOfEntries=numOfEntries)\n myList = list(community_entries)\n return myList\n\n# GET n most recent entries, all communities\n@app.route('/api/v1/entries/all/recent/', methods=['GET'])\ndef get_all_recent(numOfEntries):\n all_entries = queries.all_entries_sorted(numOfEntries=numOfEntries)\n myList = list(all_entries)\n return myList\n\n# ---- Voting Microservice ----\n\n# GET n top-scoring entries, all communities\n@app.route('/api/v1/votes/top/', methods=['GET'])\ndef get_top_scoring(numOfEntries):\n top_entries = queries.entry_by_votes(numOfEntries=numOfEntries)\n myList = list(top_entries)\n return myList\n\n\n# Report an entry's number of upvotes/downvotes, upvote or downvote the entry\n@app.route('/api/v1/votes/', methods=['GET', 'PUT', 'PATCH'])\ndef report_votes(id):\n if request.method == 'GET':\n report_votes = queries.report_votes(id=id)\n if report_votes:\n return report_votes\n else:\n return { 'message': f'Entry with id {id} does not exist' }, status.HTTP_404_NOT_FOUND\n\n # using PUT method to upvote entry\n elif request.method == 'PUT':\n up_vote_entry = queries.up_vote_entry(id=id)\n if up_vote_entry:\n return { 'message': f'Entry with id {id} has been upvoted' }, status.HTTP_200_OK\n else:\n return { 'message': f'Entry with id {id} can\\'t be upvoted' }, status.HTTP_400_BAD_REQUEST\n\n # using PATCH method to downvote entry\n elif request.method == 'PATCH':\n down_vote_entry = queries.down_vote_entry(id=id)\n if down_vote_entry:\n return { 'message': f'Entry with id {id} has been downvoted' }, status.HTTP_200_OK\n else:\n return { 'message': f'Entry with id {id} can\\'t be downvoted' }, status.HTTP_400_BAD_REQUEST\n\n# Given a list of post identifiers, return the list sorted by score\n@app.route('/api/v1/votes/scorelist', methods=['POST'])\ndef score_list():\n #entries_by_list = queries.entries_by_list(request.data)\n idList = request.json['id']\n entries_by_list = queries.entries_by_list(idList=idList)\n if entries_by_list:\n return list(entries_by_list)\n else:\n return { 'message': 'Posts could not be retrieved' }, status.HTTP_400_BAD_REQUEST\n\n# Create a new entry\ndef create_entry(entry):\n required_fields = ['id', 'title', 'bodyText', 'community', 'url', 'username', 'datePosted']\n\n if not all([field in entry for field in required_fields]):\n raise exceptions.ParseError()\n try:\n entry['id'] = queries.create_entry(**entry)\n except Exception as e:\n return { 'error': str(e) }, status.HTTP_409_CONFLICT\n\n return entry, status.HTTP_201_CREATED, {\n 'Location': f'/api/v1/entries/{entry[\"id\"]}'\n }\n\n# Filter entries given user input\ndef filter_entries(query_parameters):\n id = query_parameters.get('id')\n\n query = \"SELECT * FROM entries WHERE\"\n to_filter = []\n\n if id:\n query += ' id=? AND'\n to_filter.append(id)\n if not (id):\n raise exceptions.NotFound()\n\n query = query[:-4] + ';'\n\n results = queries._engine.execute(query, to_filter).fetchall()\n\n return list(map(dict, results))\n\n# Return entry given an id\ndef get_entry_with_id(id):\n entry = queries.entry_by_id(id=id)\n if entry:\n return entry\n else:\n raise exceptions.NotFound()\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"431908866","text":"from ctypes import cdll\nfrom ctypes import Structure\nfrom ctypes import c_int\nfrom ctypes import c_long\nfrom ctypes import c_double\nfrom ctypes import byref\nfrom ctypes import POINTER\nfrom datetime import datetime, timezone\nfrom SHDatetime_struct import Timeshift, SHDatetime, make_dt_copy\nimport sys\n\nlib = cdll.LoadLibrary('./libdt.so')\n\n\nclass MonthDay:\n month = 0\n day = 0\n\n def __init__(self,month,day):\n self.month = month\n self.day = day\n\ndef compareDTtoPyDt(dt,pdt):\n if dt.year != pdt.timetuple()[0]:\n return False\n if dt.month != pdt.timetuple()[1]:\n return False\n if dt.day != pdt.timetuple()[2]:\n return False\n if dt.hour != pdt.timetuple()[3]:\n return False\n if dt.minute != pdt.timetuple()[4]:\n return False\n if dt.second != pdt.timetuple()[5]:\n return False\n return True\n\ndef testCTimeExhaustive(lowBound,upBound):\n incr = 1 if upBound > lowBound else -1\n error = c_int(0)\n dt = SHDatetime()\n ans = c_double(-1)\n print(lowBound)\n for i in range(lowBound,upBound,incr):\n ts=c_double(i)\n lib.tryTimestampToDt(ts,0,byref(dt),byref(error))\n try:\n pts = datetime.fromtimestamp(i,tz=timezone.utc)\n if not compareDTtoPyDt(dt,pts):\n dateStr = \"year {} month:{} day:{}\".format(\n dt.year,dt.month,dt.day)\n print(\"{}___\".format(dateStr))\n return -1\n pdt = datetime(dt.year,dt.month,dt.day,dt.hour,dt.minute, dt.second\n ,tzinfo = timezone.utc)\n if error.value:\n print(\"\\ntimestamp to dt ended with error code {}\\n\".format(error.value))\n print(\"timestamp: {}\".format(ans.value))\n return -1\n lib.tryDtToTimestamp(byref(dt),byref(ans),byref(error))\n if ans.value != pdt.timestamp():\n print(\"\\nresult does not match python timestamp {}\\n\".format(ans.value))\n return -1\n if error.value:\n print(\"\\ndt to timestamp ended with error code {}\\n\".format(error.value))\n return -1\n \n\n if i % 86400 == 0:\n dateStr = \"year {} month:{} day:{}\".format(\n dt.year,dt.month,dt.day)\n print(\"{}___\".format(dateStr),end=\"\\r\",flush=True)\n if ans.value != i:\n print(\"\\nExpected value: {} actual value: {}\\n\".format(\n i,ans.value))\n return -1\n except:\n print(sys.exc_info()[1])\n print(\"i is: {}\".format(i))\n dateStr = \"year {} month:{} day:{}\".format(\n dt.year,dt.month,dt.day)\n print(\"{}___\".format(dateStr))\n return -1\n\n return 0\n\n\n\nif __name__ == \"__main__\":\n lowBound = 0\n upBound = sys.maxsize\n if len(sys.argv) > 1:\n lowBound = int(sys.argv[1])\n if len(sys.argv) > 2:\n upBound = int(sys.argv[2])\n exitCode = testCTimeExhaustive(lowBound,upBound)\n if exitCode == 0:\n print(\"Process done successfully\")\n sys.exit(exitCode)\n","sub_path":"cl_dt_all.py","file_name":"cl_dt_all.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"155124079","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\nimport json\nimport logging\nfrom typing import Sequence\nfrom urllib.parse import urlparse\n\nfrom opentelemetry.metrics import Counter, Measure, Metric\nfrom opentelemetry.sdk.metrics.export import (\n MetricRecord,\n MetricsExporter,\n MetricsExportResult,\n)\nfrom opentelemetry.sdk.util import ns_to_iso_str\n\nfrom azure_monitor import protocol, utils\nfrom azure_monitor.exporter import BaseExporter\n\nlogger = logging.getLogger(__name__)\n\n\nclass AzureMonitorMetricsExporter(BaseExporter, MetricsExporter):\n def __init__(self, **options):\n super(AzureMonitorMetricsExporter, self).__init__(**options)\n\n def export(\n self, metric_records: Sequence[MetricRecord]\n ) -> MetricsExportResult:\n envelopes = map(self.metric_to_envelope, metric_records)\n envelopes_to_export = map(\n lambda x: x.to_dict(),\n tuple(self.apply_telemetry_processors(envelopes)),\n )\n try:\n result = self._transmit(envelopes_to_export)\n if result == MetricsExportResult.FAILED_RETRYABLE:\n self.storage.put(envelopes, result)\n if result == utils.ExportResult.SUCCESS:\n # Try to send any cached events\n self._transmit_from_storage()\n return utils.get_metrics_export_result(result)\n except Exception:\n logger.exception(\"Exception occurred while exporting the data.\")\n\n def metric_to_envelope(\n self, metric_record: MetricRecord\n ) -> protocol.Envelope:\n\n if not metric_record:\n return None\n envelope = protocol.Envelope(\n ikey=self.options.instrumentation_key,\n tags=dict(utils.azure_monitor_context),\n time=ns_to_iso_str(\n metric_record.metric.get_handle(\n metric_record.label_set\n ).last_update_timestamp\n ),\n )\n envelope.name = \"Microsoft.ApplicationInsights.Metric\"\n\n data_point = protocol.DataPoint(\n ns=metric_record.metric.name,\n name=metric_record.metric.description,\n value=metric_record.aggregator.checkpoint,\n kind=protocol.DataPointType.MEASUREMENT,\n )\n\n properties = {}\n for label_tuple in metric_record.label_set.labels:\n properties[label_tuple[0]] = label_tuple[1]\n\n data = protocol.MetricData(metrics=[data_point], properties=properties)\n envelope.data = protocol.Data(base_data=data, base_type=\"MetricData\")\n return envelope\n","sub_path":"azure_monitor/src/azure_monitor/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"542110176","text":"import numpy as np\n\n\nclass LinearProgram:\n \"\"\"\n A class to store a linear program.\n\n Attributes\n ----------\n num_eq : int\n num_var : int\n A : matrix of size num_eq x num_var\n b : vector of size num_eq\n cost : np.array\n\n The LP is of the form A x = b, x >= 0.\n \"\"\"\n\n def __init__(self, A: np.array, b: np.array, cost: np.array):\n\n self.num_eq = len(A) # number of equations\n self.num_var = len(A[0]) # number of variables\n\n if len(cost) != self.num_var:\n print(\n \"Error: Number of rows of A does not match\\\n the number of rows of the cost function.\"\n )\n return\n if len(b) != self.num_eq:\n print(\"Error: Number of rows of A does not match the number of rows of b.\")\n return\n\n self.A = np.array(A)\n self.b = np.array(b)\n self.cost = np.array(cost)\n\n def print(self):\n \"Prints the system of equations.\"\n\n print(\"Minimize: \")\n for i in range(self.num_var):\n print(str(self.cost[i]) + \"*x_\" + str(i), end=\" + \")\n print(str(self.cost[self.num_var - 1]) + \"*x_\" + str(self.num_var - 1))\n\n print(\"Subject to constraints:\")\n for i in range(self.num_eq):\n for j in range(self.num_var - 1):\n print(str(self.A[i][j]) + \"*x_\" + str(j), end=\" + \")\n print(\n str(self.A[i][self.num_var - 1]) + \"*x_\" + str(self.num_var - 1),\n end=\" = \",\n )\n print(self.b[i])\n for i in range(self.num_var):\n print(\"x_\" + str(i) + \" >= 0\")\n\n\nclass SimplexMethod:\n \"\"\"\n A class for implementing Simplex Method.\n\n Attributes\n ----------\n lp: LinearProgram\n basis_columns:\n vertex\n B_inv\n\n \"\"\"\n\n def __init__(self, lp: LinearProgram, basis_columns: np.array):\n\n self.lp = lp\n self.basis_columns = np.array(basis_columns)\n self.update_inv_naive()\n self.calculate_vertex()\n\n def update_inv_naive(self):\n self.B_inv = np.linalg.inv(self.lp.A[:, self.basis_columns])\n\n def calculate_vertex(self):\n\n self.vertex = np.zeros(self.lp.num_var)\n\n # aux_vertex = B^{-1} * b\n aux_vertex = np.matmul(self.B_inv, self.lp.b)\n\n # put the values of `aux_vertex` into appropriate \"spots\".\n for i in range(self.lp.num_var):\n if i in self.basis_columns:\n self.vertex[i] = aux_vertex[(np.where(self.basis_columns == i))[0]]\n\n def cost(self):\n return np.dot(self.lp.cost, self.vertex)\n\n def reduced_cost_naive(self, index: int):\n \"Returns the reduced cost in the direction `j`: c'_j = c_j - c'_B * B^{-1} * A_j\"\n cB = self.lp.cost[self.basis_columns]\n reduced_cost = self.lp.cost[index] - np.matmul(\n cB, np.matmul(self.B_inv, self.lp.A[:, index])\n )\n return reduced_cost\n\n def step(self, i: int):\n\n # u = B^{-1} * A_i\n u = np.matmul(self.B_inv, self.lp.A[:, i])\n\n # values in `u` that are positive\n u_pos = u[u > 0]\n\n # If no-coordinates of `u` are positive,\n # then there is no vertex in this direction.\n if len(u_pos) == 0:\n return False\n\n # Basis vectors corresponding to the positive entries in `u`\n b_pos = self.basis_columns[u > 0]\n\n # Coordinates of `x` corresponding to the positive values of `u`\n x = self.vertex[b_pos]\n\n # normalize the positive coordinates and find the min values\n thetas = x / u_pos\n theta_argmin = np.argmin(thetas)\n theta_min = min(thetas)\n\n # Replace the i^th basis_column with the `theta_argmin` one\n self.basis_columns[theta_argmin] = i\n self.update_inv_naive()\n self.calculate_vertex()\n\n # Coordinates of the new vertex\n # self.vertex = [\n # self.vertex[i] - theta_min * u[i] for i in range(len(self.vertex))\n # ]\n # self.vertex[theta_argmin] = theta_min\n\n # new_vertex = np.zeros(self.lp.num_var)\n # for i in range(self.lp.num_eq):\n # new_vertex[self.basis_columns[i]] = (\n # self.vertex[self.basis_columns[i]] - theta_min * u[i]\n # )\n # new_vertex[self.basis_columns[theta_argmin]] = theta_min\n # self.vertex = new_vertex\n\n return True\n\n def solve(self, reduced_cost_calc=reduced_cost_naive):\n # Loop over the indices `i` which are not in one of the basis_columns.\n for i in range(self.lp.num_var):\n if not (i in self.basis_columns):\n\n # Calculate the reduced cost in the `i` direction.\n reduced_cost = self.reduced_cost_naive(i)\n\n # If the reduced cost is negative,\n # then move in the direction of `i` to the next vertex.\n if reduced_cost < 0:\n # in the direction of `i`\n # if search for the next direction is succesful,\n # restart the process from the new vertex\n # else the cost is -infinity\n if self.step(i):\n break\n return -1\n\n # If all reduced costs are non-negative\n # then `i` is the optimal solution\n return i\n\n self.solve()\n\n def print_solution(self):\n\n print(\"-\" * 20)\n self.lp.print()\n\n print(\"-\" * 20)\n print(\"Solution:\")\n for i in range(len(self.vertex)):\n print(\"x_\" + str(i) + \" = \" + str(round(self.vertex[i], 2)))\n print(\"Minimal cost = \", round(self.cost(), 2))\n return\n\n\nlp = LinearProgram(\n A=[[1, 2, 2, 1, 0, 0], [2, 1, 2, 0, 1, 0], [2, 2, 1, 0, 0, 1]],\n b=[20, 20, 20],\n cost=[-10, -12, -12, 0, 0, 0],\n)\n\nsimplex = SimplexMethod(lp, basis_columns=[3, 4, 5])\n\nsimplex.solve()\n\nsimplex.print_solution()\n","sub_path":"simplex.py","file_name":"simplex.py","file_ext":"py","file_size_in_byte":5950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"449064271","text":"# vim: ai ts=4 sts=4 et sw=4\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom django.db import models\n\nfrom filebrowser_safe.fields import FileBrowseFormField\n\nfrom clubhouse.core import widgets\n\nclass FileBrowseImageField(models.ImageField):\n def __init__(self,*args,**kwargs):\n self.extensions = kwargs.pop('extensions', '')\n super(FileBrowseImageField,self).__init__(*args,**kwargs)\n\n def formfield(self, **kwargs):\n attrs = {}\n attrs[\"directory\"] = self.upload_to\n attrs[\"extensions\"] = self.extensions\n attrs[\"format\"] = 'Image'\n defaults = {\n 'form_class': FileBrowseFormField,\n 'widget': widgets.FileBrowseImageWidget(attrs=attrs),\n 'directory': self.upload_to,\n 'extensions': self.extensions,\n 'format': 'Image'\n }\n defaults.update(kwargs)\n return super(FileBrowseImageField, self).formfield(**defaults)\n","sub_path":"clubhouse/core/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"617279207","text":"from enum import Enum\n\n\nclass HTTPMethod(Enum):\n \"\"\"Enum with http methods\"\"\"\n \n POST = 'POST'\n GET = 'GET'\n PUT = 'PUT'\n DELETE = 'DELETE'\n\n\nclass FileType(Enum):\n \"\"\"Enum with file sheet types\"\"\"\n\n EXCEL = 'EXCEL'\n CSV = 'CSV'\n\n\nclass HeaderOption(Enum):\n \"\"\"Enum with options to fine column headers\"\"\"\n\n DEFAULT = 'DEFAULT'\n FIND = 'FIND'\n EXACT = 'EXACT'\n\n\nclass TaskType(Enum):\n \"\"\"Enum with types of tasks\"\"\"\n\n IMPORT_CREATE = 'IMPORT_CREATE'\n IMPORT_EDIT = 'IMPORT_EDIT'\n BULK_EDIT = 'BULK_EDIT'\n\n\nclass ExecutionType(Enum):\n \"\"\"Enum with the types of job executions\"\"\"\n \n NOW = 'NOW'\n SCHEDULED = 'SCHEDULED'\n RECURRING = 'RECURRING'\n\n\nclass ProductStatus(Enum):\n \"\"\"Enum with product statuses\"\"\"\n\n ACTIVE = 'ACTIVE'\n DRAFT = 'DRAFT'\n ARCHIVED = 'ARCHIVED'\n\n\nclass JobStatus(Enum):\n SUBMITTED = 'SUBMITTED'\n PREPARING = 'PREPARING'\n RUNNING = 'RUNNING'\n COMPLETED = 'COMPLETED'\n PARTIAL_COMPLETE = 'PARTIALLY COMPLETED'\n FAILED = 'FAILED'","sub_path":"src/datamodel/custom_enums.py","file_name":"custom_enums.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"28404363","text":"################################################################################\n# The MIT License\n#\n# Copyright (c) 2019-2021, Prominence AI, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n################################################################################\n\n#!/usr/bin/env python\n\nimport sys\nsys.path.insert(0, \"../../\")\nfrom dsl import *\n\nuri_file = \"../../test/streams/sample_1080p_h264.mp4\"\n\n# Filespecs for the Primary GIE and IOU Trcaker\nprimary_infer_config_file = '../../test/configs/config_infer_primary_nano.txt'\nprimary_model_engine_file = '../../test/models/Primary_Detector_Nano/resnet10.caffemodel_b8_gpu0_fp16.engine'\ntracker_config_file = '../../test/configs/iou_config.txt'\n\nPGIE_CLASS_ID_VEHICLE = 0\nPGIE_CLASS_ID_BICYCLE = 1\nPGIE_CLASS_ID_PERSON = 2\nPGIE_CLASS_ID_ROADSIGN = 3\n\nTILER_WIDTH = DSL_DEFAULT_STREAMMUX_WIDTH\nTILER_HEIGHT = DSL_DEFAULT_STREAMMUX_HEIGHT\nWINDOW_WIDTH = DSL_DEFAULT_STREAMMUX_WIDTH\nWINDOW_HEIGHT = DSL_DEFAULT_STREAMMUX_HEIGHT\n#WINDOW_WIDTH = 1280\n#WINDOW_HEIGHT = 720\n\n## \n# Function to be called on XWindow KeyRelease event\n## \ndef xwindow_key_event_handler(key_string, client_data):\n print('key released = ', key_string)\n if key_string.upper() == 'P':\n dsl_pipeline_pause('pipeline')\n elif key_string.upper() == 'R':\n dsl_pipeline_play('pipeline')\n elif key_string.upper() == 'Q' or key_string == '\u001B' or key_string == '\u0003':\n dsl_main_loop_quit()\n \n## \n# Function to be called on XWindow Delete event\n## \ndef xwindow_delete_event_handler(client_data):\n print('delete window event')\n dsl_main_loop_quit()\n\n## \n# Function to be called on End-of-Stream (EOS) event\n## \ndef eos_event_listener(client_data):\n print('Pipeline EOS event')\n dsl_main_loop_quit()\n\n## \n# Function to be called on every change of Pipeline state\n## \ndef state_change_listener(old_state, new_state, client_data):\n print('previous state = ', old_state, ', new state = ', new_state)\n if new_state == DSL_STATE_PLAYING:\n dsl_pipeline_dump_to_dot('pipeline', \"state-playing\")\n\n## \n# Function to create all required RGBA Color Types\n## \ndef create_colors():\n retval = dsl_display_type_rgba_color_new('opaque-red', red=1.0, green=0.0, blue=0.0, alpha = 0.2)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('opaque-yellow', red=1.0, green=1.0, blue=0.0, alpha = 0.1)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('full-grey', red=0.5, green=0.5, blue=0.5, alpha = 1.0)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('opaque-black', red=0.0, green=0.0, blue=0.0, alpha = 0.2)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('full-white', red=1.0, green=1.0, blue=1.0, alpha = 1.0)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('opaque-white', red=1.0, green=1.0, blue=1.0, alpha = 1.0)\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_color_new('full-blue', red=0.0, green=0.0, blue=1.0, alpha = 1.0)\n\n return retval\n\n \n## \n# Function to create all required RGBA Display Types\n## \ndef create_fonts_text_and_shapes():\n\n ## Import Note: all coordinates and dimensions are relative to the Stream Muxer and Tiler Dimensions\n retval = dsl_display_type_rgba_font_new('arial-15-white', font='arial', size=15, color='full-white')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n retval = dsl_display_type_rgba_font_new('arial-20-blue', font='arial', size=20, color='full-blue')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # New RGBA Rectangle to use as a background for summation display. Using the full black with alpha=1.0\n retval = dsl_display_type_rgba_rectangle_new('grey-rectangle', left=10, top=45, width=190, height=110, \n border_width=0, color='full-grey', has_bg_color=True, bg_color='full-grey')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # A second RGBA Rectangle to use as a dropped shadow for summation display. Using the opaque black\n retval = dsl_display_type_rgba_rectangle_new('black-shadow', left=16, top=51, width=190, height=110, \n border_width=0, color='opaque-black', has_bg_color=True, bg_color='opaque-black')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # A new RGBA Circle to be used as a custom arrow head.\n retval = dsl_display_type_rgba_circle_new('blue-circle', x_center=530, y_center=50, radius=5, \n color='full-blue', has_bg_color=True, bg_color='full-blue')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n retval = dsl_display_type_rgba_line_new('blue-line', x1=530, y1=50, x2=730, y2=50, width=2, color='full-blue')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n retval = dsl_display_type_rgba_text_new('blue-text', 'Shared Trigger Area', x_offset=733, y_offset=30, \n font='arial-20-blue', has_bg_color=False, bg_color=None)\n\n # New RGBA Rectangle to use with an ODE Area as Trigger criteria, shared between Person and Vehicle Class Id's \n retval = dsl_display_type_rgba_rectangle_new('shared-rectangle', left=500, top=0, width=60, height=1089, \n border_width=0, color='opaque-yellow', has_bg_color=True, bg_color='opaque-yellow')\n if retval != DSL_RETURN_SUCCESS:\n return retval\n \n # A second RGBA Rectangle use with a second ODE Area, used by the Person Class Id only\n return dsl_display_type_rgba_rectangle_new('person-rectangle', left=200, top=0, width=10, height=1089, \n border_width=0, color='opaque-yellow', has_bg_color=True, bg_color='opaque-yellow')\n \n## \n# \n## \ndef main(args):\n\n # Since we're not using args, we can Let DSL initialize GST on first call\n while True:\n\n # create all required RGBA colors\n retval = create_colors(); \n if retval != DSL_RETURN_SUCCESS:\n break\n \n # create all required RGBA fonts, text and shapes for adding display metadata\n retval = create_fonts_text_and_shapes(); \n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create a new Action to add all display data to every frame\n retval = dsl_ode_action_display_meta_add_many_new('add-display-meta', display_types=\n ['grey-rectangle', 'black-shadow', 'blue-circle', 'blue-line', 'blue-text', None])\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create an Always triger to overlay our Display Types on every frame - single source, so no filter\n retval = dsl_ode_trigger_always_new('always-trigger', source=None, when=DSL_ODE_PRE_OCCURRENCE_CHECK)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('always-trigger', action='add-display-meta')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # Create two areas to be used as criteria for ODE Occurrence. The first area\n # will be for the Person class alone... and defines a vertical rectangle to \n # the left of the pedestrian sidewalk. The pixel values are relative to the\n # This area's background will be shaded yellow for caution\n retval = dsl_ode_area_inclusion_new('person-area', 'person-rectangle', display=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # The second area will be shared by both Person and Vehicle classes... and defines\n # a vertical area/rectangle to the right of the sidewalk and left of the street\n # This area's background will be shaded yellow for caution\n retval = dsl_ode_area_inclusion_new('shared-area', 'shared-rectangle', display=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create a new Fill Action that will fill the Object's rectangle with a shade of red to indicate that\n # overlap with one or more of the defined Area's has occurred, i.e. ODE occurrence. The action will be\n # used with both the Person and Car class Ids to indicate thay have entered the area of caution\n retval = dsl_ode_action_fill_object_new('red-fill-action', 'opaque-red')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Create a new Capture Action to capture the full-frame to jpeg image, and save to file. \n # The action will be triggered on firt occurrence of a bicycle and will be save to the current dir.\n retval = dsl_ode_action_capture_frame_new('bicycle-capture', outdir=\"./\", annotate=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # Create a new Action used to display all Object detection summations for each frame. Use the classId\n # to add an additional vertical offset so the one action can be shared accross classId's\n retval = dsl_ode_action_display_new('display-action', x_offset=24, y_offset=55, y_offset_with_classId=True,\n font='arial-15-white', has_bg_color=False, bg_color=None)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n \n # New Occurrence Trigger, filtering on the Person Class Id, with no limit on the number of occurrences\n # Add the two Areas as Occurrence (overlap) criteria and the action to Fill the background red on occurrence\n retval = dsl_ode_trigger_occurrence_new('person-area-overlap', source=None, class_id=PGIE_CLASS_ID_PERSON, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_area_add_many('person-area-overlap', areas=['person-area', 'shared-area', None])\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('person-area-overlap', action='red-fill-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New Occurrence Trigger, filtering on the Vehicle ClassId, with no limit on the number of occurrences\n # Add the single Shared Area and the action to Fill the background red on occurrence \n retval = dsl_ode_trigger_occurrence_new('vehicle-area-overlap', source=None, class_id=PGIE_CLASS_ID_VEHICLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_area_add('vehicle-area-overlap', area='shared-area')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('vehicle-area-overlap', action='red-fill-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New Occurrence Trigger, filtering on the Bicycle ClassId, with a limit of one occurrence\n # Add the capture-frame action to the first occurrence event\n retval = dsl_ode_trigger_occurrence_new('bicycle-first-occurrence', source=None, class_id=PGIE_CLASS_ID_BICYCLE, limit=1)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('bicycle-first-occurrence', action='bicycle-capture')\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New ODE Triggers for Object summation - i.e. new ODE occurrence on detection summation.\n # Each Trigger will share the same ODE Display Action\n retval = dsl_ode_trigger_summation_new('Vehicles:', source=None, class_id=PGIE_CLASS_ID_VEHICLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('Vehicles:', action='display-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_summation_new('Bicycles:', source=None, class_id=PGIE_CLASS_ID_BICYCLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('Bicycles:', action='display-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_summation_new('Pedestrians:', source=None, class_id=PGIE_CLASS_ID_PERSON, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('Pedestrians:', action='display-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # A hide action to use with two occurrence Triggers, filtering on the Person Class Id and Vehicle Class Id\n # We will use an every occurrece Trigger to hide the Display Text and Rectangle Border for each object detected\n # We will leave the Bicycle Display Text and Border untouched\n retval = dsl_ode_action_hide_new('hide-action', text=True, border=True)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_occurrence_new('person-every-occurrence', source=None, class_id=PGIE_CLASS_ID_PERSON, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('person-every-occurrence', action='hide-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_occurrence_new('vehicle-every-occurrence', source=None, class_id=PGIE_CLASS_ID_VEHICLE, limit=0)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_ode_trigger_action_add('vehicle-every-occurrence', action='hide-action')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New ODE Pad Probe Handler to handle all ODE Triggers with their Areas and Actions \n retval = dsl_pph_ode_new('ode-hanlder')\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_pph_ode_trigger_add_many('ode-hanlder', triggers=[\n 'vehicle-area-overlap',\n 'person-area-overlap', \n 'bicycle-first-occurrence',\n 'always-trigger',\n 'Vehicles:',\n 'Bicycles:',\n 'Pedestrians:',\n 'person-every-occurrence',\n 'vehicle-every-occurrence',\n None])\n if retval != DSL_RETURN_SUCCESS:\n break\n \n \n ############################################################################################\n #\n # Create the remaining Pipeline components\n \n # New URI File Source using the filespec defined above\n retval = dsl_source_uri_new('uri-source', uri_file, False, 0, 0, 0)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New Primary GIE using the filespecs above with interval = 0\n retval = dsl_gie_primary_new('primary-gie', primary_infer_config_file, primary_model_engine_file, 4)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New IOU Tracker, setting max width and height of input frame\n retval = dsl_tracker_iou_new('iou-tracker', tracker_config_file, 480, 272)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New Tiled Display, setting width and height, use default cols/rows set by source count\n retval = dsl_tiler_new('tiler', TILER_WIDTH, TILER_HEIGHT)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n retval = dsl_tiler_pph_add('tiler', handler='ode-hanlder', pad=DSL_PAD_SINK)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # New OSD with clock and text enabled... using default values.\n retval = dsl_osd_new('on-screen-display', True, True)\n if retval != DSL_RETURN_SUCCESS:\n break\n \n # New Window Sink, 0 x/y offsets and same dimensions as Tiled Display\n retval = dsl_sink_window_new('window-sink', 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Add all the components to our pipeline\n retval = dsl_pipeline_new_component_add_many('pipeline', \n ['uri-source', 'primary-gie', 'iou-tracker', 'tiler', 'on-screen-display', 'window-sink', None])\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Add the XWindow event handler functions defined above\n retval = dsl_pipeline_xwindow_key_event_handler_add(\"pipeline\", xwindow_key_event_handler, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_pipeline_xwindow_delete_event_handler_add(\"pipeline\", xwindow_delete_event_handler, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n ## Add the listener callback functions defined above\n retval = dsl_pipeline_state_change_listener_add('pipeline', state_change_listener, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n retval = dsl_pipeline_eos_listener_add('pipeline', eos_event_listener, None)\n if retval != DSL_RETURN_SUCCESS:\n break\n\n # Play the pipeline\n retval = dsl_pipeline_play('pipeline')\n if retval != DSL_RETURN_SUCCESS:\n break\n\n dsl_main_loop_run()\n retval = DSL_RETURN_SUCCESS\n break\n\n # Print out the final result\n print(dsl_return_value_to_string(retval))\n\n # Cleanup all DSL/GST resources\n dsl_delete_all()\n \nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","sub_path":"examples/python/ode_triggers_areas_actions_display_types.py","file_name":"ode_triggers_areas_actions_display_types.py","file_ext":"py","file_size_in_byte":18262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"108754124","text":"import os\n\nimport findspark\nimport pytest\n\n\nclass SparkHome(object):\n\n def __init__(self, pytest_config):\n self.config = pytest_config\n\n self._path, source_name = self._detect_path()\n if self._path:\n self._path = os.path.abspath(self._path)\n if not os.path.exists(self._path):\n raise OSError(\n \"SPARK_HOME path specified in %s does not exist: %s\"\n % (source_name, self._path))\n\n @property\n def path(self):\n return self._path\n\n @property\n def version(self):\n if self.path:\n return self._get_spark_version(self.path)\n\n def _get_spark_version(self, spark_home):\n release_info_filename = os.path.join(spark_home, 'RELEASE')\n if os.path.exists(release_info_filename):\n with open(release_info_filename) as release_info:\n return release_info.read()\n\n def _locations(self):\n yield (\n self.config.option.spark_home,\n 'config (command line option \"--spark_home\")',\n )\n yield (self.config.getini('spark_home'), 'config (pytest.ini)')\n yield (os.environ.get('SPARK_HOME'), 'ENV')\n\n def _detect_path(self):\n for path, description in self._locations():\n if path:\n return path, description\n return None, None\n\n\ndef pytest_addoption(parser):\n parser.addini('spark_home', 'Spark install directory (SPARK_HOME).')\n parser.addoption(\n '--spark_home',\n dest='spark_home',\n help='Spark install directory (SPARK_HOME).',\n )\n\n\ndef pytest_configure(config):\n spark_home = SparkHome(config).path\n\n if spark_home:\n findspark.init(spark_home)\n\n\ndef pytest_report_header(config, startdir):\n spark_ver = SparkHome(config).version\n if spark_ver:\n spark_ver = spark_ver.strip().replace('\\n', ' | ')\n return \"spark version -- \" + spark_ver\n\n\ndef reduce_logging(sc):\n \"\"\"Reduce logging in SparkContext instance.\"\"\"\n\n logger = sc._jvm.org.apache.log4j\n logger.LogManager.getLogger(\"org\").setLevel(logger.Level.OFF)\n logger.LogManager.getLogger(\"akka\").setLevel(logger.Level.OFF)\n\n\n@pytest.fixture(scope='session')\ndef _spark_session():\n \"\"\"Internal fixture for SparkSession instance.\n\n Yields SparkSession instance if it is supported by the pyspark\n version, otherwise yields None.\n\n Required to correctly initialize `spark_context` fixture after\n `spark_session` fixture.\n\n ..note::\n It is not possible to create SparkSession from the existing\n SparkContext.\n \"\"\"\n\n try:\n from pyspark.sql import SparkSession\n except ImportError:\n yield\n else:\n session = SparkSession.builder.enableHiveSupport().getOrCreate()\n yield session\n session.stop()\n\n\n@pytest.fixture(scope='session')\ndef spark_context(_spark_session):\n \"\"\"Return a SparkContext instance with reduced logging\n (session scope).\n \"\"\"\n\n if _spark_session is None:\n from pyspark import SparkContext\n\n # pyspark 1.x: create SparkContext instance\n sc = SparkContext()\n else:\n # pyspark 2.x: get SparkContext from SparkSession fixture\n sc = _spark_session.sparkContext\n\n reduce_logging(sc)\n yield sc\n\n if _spark_session is None:\n sc.stop() # pyspark 1.x: stop SparkContext instance\n\n\n@pytest.fixture(scope='session')\ndef spark_session(_spark_session):\n \"\"\"Return a Hive enabled SparkSession instance with reduced logging\n (session scope).\n\n Available from Spark 2.0 onwards.\n \"\"\"\n\n if _spark_session is None:\n raise Exception(\n 'The \"spark_session\" fixture is only available on spark 2.0 '\n 'and above. Please use the spark_context fixture and instanciate '\n 'a SQLContext or HiveContext from it in your tests.'\n )\n else:\n reduce_logging(_spark_session.sparkContext)\n yield _spark_session\n","sub_path":"pytest_spark/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"98965991","text":"####################\nimport requests\nimport qrcode\nfrom flask import Flask\nfrom flask import render_template\n####################\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n# order\n@app.route('/- ')\ndef order(item=None):\n # fetch the correct price here\n import lib.price as price\n can_price = price.get()\n url = 'bitcoincash:qz8zcxumuzd8fx4cxc73qlhs8kta4jv6wu9knfn567?amount='\n url += str(can_price)\n img = qrcode.make(url)\n img.save('static/qr.png')\n return render_template('order.html', item=item, price=round(can_price, 4))\n\n####################\n# checking the payment\n\napp.run(debug=True, port=666, host='127.0.0.1')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"511252227","text":"import speech_recognition as sr # import the library\r\nimport webbrowser as wb #\r\n\r\n\r\n\r\nchrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'\r\n\r\nr = sr.Recognizer() # initialize recognizer\r\n\r\nwith sr.Microphone() as source: # mention source it will be either Microphone or audio files.\r\n print('Say Something!')\r\n audio = r.listen(source) # listen to the source\r\n print('done,')\r\n\r\n\r\ntry:\r\n text = r.recognize_google(audio) # use recognizer to convert our audio into text part\r\n lang = 'en'\r\n print(text)\r\n if 'search in google' in text.lower():\r\n f_text = 'https://www.google.co.in/search?q=' + text[16:]\r\n wb.get(chrome_path).open(f_text)\r\n elif 'search website' in text.lower():\r\n wb.get(chrome_path).open(text[14:])\r\n else:\r\n print(text)\r\n\r\n\r\nexcept:\r\n print(\"xmis amocnoba ver moxerxda\") # In case of voice not recognized clearly\r\n","sub_path":"main3.py","file_name":"main3.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"252195309","text":"#coding:utf8\nfrom flask import jsonify,redirect, url_for, session, request, render_template, Blueprint\nimport copy\nimport model\nimport jsons\n\nac = Blueprint('star', __name__)\n\n@ac.route('/action/star/
')\ndef star(urlid):\n if 'username' not in session:\n return redirect(url_for('account.login'))\n else:\n userid = session['id']\n db = model.star(userid, urlid)\n if db.star() == True:\n return redirect(url_for('index.index'))\n else:\n errs = copy.copy(jsons.err)\n errs['decription'] = 'start false'\n return jsonify(errs)\n\n@ac.route('/action/unstar/')\ndef unstar(urlid):\n if 'username' not in session:\n return redirect(url_for('account.login'))\n else:\n userid = session['id']\n db = model.star(userid, urlid)\n if db.unstar() == True:\n return redirect(url_for('index.index'))\n else:\n errs = copy.copy(jsons.err)\n errs['decription'] = 'unstart false'\n return jsonify(errs)\n\n@ac.route('/user//stars')\ndef stars(username):\n userid = model.user(username).get()[0]\n db_up = model.update(userid).updateStars()\n db_stars = model.star(userid).get_stars()\n stars = {\n 'page':'stars',\n 'sum':len(db_stars),\n 'url':db_stars\n }\n return jsonify(stars)","sub_path":"easyurl/webSite/controllers/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"620661838","text":"k = 2\nkeywords = [\"anacell\", \"betacellular\", \"cetracular\", \"deltacellular\", \"eurocell\"]\nreviews = [\n \"I love anacell Best services; Best services provided by anacell\",\n \"betacellular has great services\",\n \"deltacellular provides much better services than betacellular\",\n \"cetracular is worse than anacell\",\n \"Betacellular is better than deltacellular.\",\n]\n\nimport re\nfrom collections import Counter\nimport heapq\n\nclass Element:\n def __init__(self, word, freq):\n self.word = word\n self.freq = freq\n \n def __lt__(self, other):\n if self.freq == other.freq:\n return self.word > other.word\n return self.freq < other.freq\n\ndef topKFrequent(k, keywords, reviews):\n '''\n k: int\n keywwords: list of string\n reviews: list of string\n '''\n word_list = []\n \n for review in reviews:\n word_list += list(review.lower().replace('[^a-z0-9]', '').split())\n \n print (word_list)\n count = Counter(word_list)\n \n heap = []\n \n for word, freq in count.items():\n if word in keywords:\n heapq.heappush(heap, Element(word, freq))\n if len(heap) > k:\n heapq.heappop(heap)\n \n return [heapq.heappop(heap).word for _ in range(k)][::-1]\n \n\nprint(topKFrequent(k, keywords, reviews))","sub_path":"ama_oa/10_top_k_frequent_mentioned_keywords.py","file_name":"10_top_k_frequent_mentioned_keywords.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"651123471","text":"import numpy as np\n\nimport keras\nfrom keras import backend as K\nfrom keras.engine.topology import Layer\n\nfrom keras.models import Sequential\n\nimport tensorflow as tf\n\n\n\nclass TaylorMap(Layer):\n def __init__(self, output_dim, order=1,\n weights_regularizer = None,\n initial_weights = None,\n aperture = 50e-5,\n **kwargs):\n self.output_dim = output_dim\n self.order = order\n self.initial_weights = initial_weights\n self.weights_regularizer = weights_regularizer\n self.aperture = aperture\n \n \n super(TaylorMap, self).__init__(**kwargs)\n\n\n def build(self, input_shape):\n input_dim = input_shape[1]\n self.input_dim = input_dim\n \n \n nsize = 1\n self.W = []\n self.nsizes = [nsize]\n \n for i in range(self.order+1):\n if self.initial_weights is None:\n initial_weight_value = np.zeros((nsize, self.output_dim))\n else:\n initial_weight_value = self.initial_weights[i]\n nsize*=input_dim\n self.nsizes.append(nsize)\n self.W.append(K.variable(initial_weight_value))\n\n if self.initial_weights is None:\n self.W[1] = (K.variable(np.eye(N=input_dim, M=self.output_dim)))\n\n self.trainable_weights = self.W\n\n return\n\n def call(self, x, mask=None):\n ans = self.W[0]\n tmp = x\n x_vectors = tf.expand_dims(x, -1)\n \n # particle loss, nan for lost particle\n # get x coordinate\n tmp_x, tmp_xp = tf.unstack(x, axis=1) \n aper = tf.constant(self.aperture, shape=None)\n # find particle outside aperture\n condition = tf.greater_equal(abs(tmp_x), aper)\n # set nan for x for lost particles\n res = tf.where(condition, np.nan, tmp_x)\n # join new x coordiantes with xp coordinates\n tmp = tf.stack([res,tmp_xp], axis=1 )\n \n # layer transformation\n for i in range(1, self.order+1):\n ans = ans + K.dot(tmp, self.W[i])\n\n if(i == self.order):\n continue\n xext_vectors = tf.expand_dims(tmp, -1)\n x_extend_matrix = tf.matmul(x_vectors, xext_vectors, adjoint_a=False, adjoint_b=True)\n tmp = tf.reshape(x_extend_matrix, [-1, self.nsizes[i+1]])\n\n if self.weights_regularizer:\n self.add_loss(self.weights_regularizer(self.W))\n \n \n return ans\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], self.output_dim)\n\n\n def get_output_shape_for(self, input_shape):\n return (input_shape[0], self.output_dim)\n","sub_path":"tm_pnn/layers/Taylor_Map_loss_method_nan.py","file_name":"Taylor_Map_loss_method_nan.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"384027291","text":"# Copyright 2017 Red Hat, 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#\n\n\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\n\nfrom tripleo_common.image import base\n\nif sys.version_info[0] < 3:\n import codecs\n _open = open\n open = codecs.open\n\n\nclass KollaImageBuilder(base.BaseImageManager):\n \"\"\"Build images using kolla-build\"\"\"\n\n logger = logging.getLogger(__name__ + '.KollaImageBuilder')\n handler = logging.StreamHandler(sys.stdout)\n\n @staticmethod\n def imagename_to_regex(imagename):\n if not imagename:\n return\n # remove any namespace from the start\n imagename = imagename.split('/')[-1]\n\n # remove any tag from the end\n imagename = imagename.split(':')[0]\n\n # remove supported base names from the start\n imagename = re.sub(r'^(centos|rhel)-', '', imagename)\n\n # remove install_type from the start\n imagename = re.sub(r'^(binary|source|rdo|rhos)-', '', imagename)\n\n # what results should be acceptable as a regex to build one image\n return imagename\n\n def build_images(self, kolla_config_files=None):\n\n cmd = ['kolla-build']\n if kolla_config_files:\n for f in kolla_config_files:\n cmd.append('--config-file')\n cmd.append(f)\n\n container_images = self.load_config_files(self.CONTAINER_IMAGES) or []\n container_images.sort(key=lambda i: i.get('imagename'))\n for i in container_images:\n image = self.imagename_to_regex(i.get('imagename'))\n if image:\n cmd.append(image)\n\n self.logger.info('Running %s' % ' '.join(cmd))\n env = os.environ.copy()\n process = subprocess.Popen(cmd, env=env)\n process.wait()\n if process.returncode != 0:\n raise subprocess.CalledProcessError(process.returncode, cmd)\n","sub_path":"tripleo_common/image/kolla_builder.py","file_name":"kolla_builder.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"206677358","text":"import unittest\nimport math\n\nfrom . import quaternion\n\n\nclass QuaternionTest(unittest.TestCase):\n\n def test_multiply(self):\n qa = [1, 0, 0, 0]\n qb = [0, 1, 0, 0]\n qc = quaternion.multiply(qa, qb)\n self.assertEqual(qc, qb) # identity\n\n qd = quaternion.multiply(qb, qb)\n self.assertEqual(qd, [-1, 0, 0, 0]) # twice rotation by 90deg\n\n qdd = quaternion.multiply(qd, qd)\n self.assertEqual(qdd, qa) # identity\n\n# vim: expandtab sw=4 ts=4\n","sub_path":"osgar/lib/test_quaternion.py","file_name":"test_quaternion.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"595597698","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author : Joshua\n@Time : 2018/9/5 18:42\n@File : proxy_manager.py\n@Desc : 代理池管理,调度抓取、验证、入库\n\"\"\"\n\nfrom multiprocessing import Value, Queue, Process\nfrom api.apiServer import start_api_server\nfrom proxy_pipeline import SqlitePipeline\n\nfrom proxy_validator import ValidatorScheduler, Validator\nfrom proxy_crawler import start_proxycrawl\n\nfrom setting import TASK_QUEUE_SIZE\n\ndef start_all():\n myip = Validator.get_myip()\n DB_PROXY_NUM = Value('i', 0)\n task_queue = Queue(maxsize=TASK_QUEUE_SIZE)\n verified_queue = Queue()\n\n process_list =[]\n p0 = Process(target=start_api_server)\n process_list.append(p0)\n p1 = Process(target=start_proxycrawl, args=(task_queue, DB_PROXY_NUM, myip))\n process_list.append(p1)\n p2 = Process(target=ValidatorScheduler.validator, args=(task_queue, verified_queue, myip))\n process_list.append(p2)\n p3 = Process(target=SqlitePipeline.save_data, args=(verified_queue, DB_PROXY_NUM))\n process_list.append(p3)\n\n for i in process_list:\n i.daemon = True\n i.start()\n\n for i in process_list:\n i.join()\n\nif __name__ == \"__main__\":\n start_all()","sub_path":"spider/strong_spider/spider/antispider/proxypool/proxy_manager.py","file_name":"proxy_manager.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"379787666","text":"\"\"\"Свои типы полей\"\"\"\n\nfrom django.db import models\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\nclass OrderField(models.PositiveIntegerField):\n \"\"\"\n Собственное поле сортировки (для определения порядка для содержимого курсов).\n Наследуэмся от PositiveIntegerField и реализовуем две дополнительные функции:\n 1) автоматическое назначение порядкового номера, если он не был задан\n явно. Когда создается новый объект и пользователь не указывает порядок,\n поле будет заполняться автоматически, основываясь на том, сколько\n объектов уже создано для модуля. Например, если уже есть два объекта\n с порядковыми номерами 1 и 2, то новому будет присвоен 3;\n 2) сортировка объектов по порядку номеров. Модули курсов и содержимое\n модулей всегда будут возвращаться отсортированными внутри своего\n родительского объекта.\n \"\"\"\n\n def __init__(self, for_fields=None, *args, **kwargs):\n self.for_fields = for_fields\n super(OrderField, self).__init__(*args, **kwargs)\n\n def pre_save(self, model_instance, add):\n if getattr(model_instance, self.attname) is None:\n # Значение пусто.\n try:\n qs = self.model.objects.all()\n if self.for_fields:\n # Фильтруем объекты с такими же значениями полей, перечисленных в \"for_fields\".\n query = {field: getattr(model_instance, field) for field in self.for_fields}\n qs = qs.filter(**query)\n # Получаем заказ последнего объекта.\n last_item = qs.latest(self.attname)\n value = last_item.order + 1\n except ObjectDoesNotExist:\n value = 0\n setattr(model_instance, self.attname, value)\n return value\n else:\n return super(OrderField, self).pre_save(model_instance, add)\n","sub_path":"myeduca/src/courses/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"427704385","text":"\"\"\"\nSupport for Xiaomi Mi Home Air Conditioner Companion (AC Partner)\n\nFor more details about this platform, please refer to the documentation\nhttps://home-assistant.io/components/climate.xiaomi_miio\n\"\"\"\nimport logging\nimport asyncio\nfrom functools import partial\nfrom datetime import timedelta\nimport voluptuous as vol\n\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.entity import ToggleEntity\nfrom homeassistant.components.climate import (\n PLATFORM_SCHEMA, ClimateDevice, ATTR_TARGET_TEMP_HIGH,\n ATTR_TARGET_TEMP_LOW, ATTR_OPERATION_MODE,\n SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_HIGH,\n SUPPORT_TARGET_TEMPERATURE_LOW, SUPPORT_OPERATION_MODE, SUPPORT_FAN_MODE,\n SUPPORT_SWING_MODE, SUPPORT_ON_OFF, )\nfrom homeassistant.const import (\n TEMP_CELSIUS, ATTR_TEMPERATURE, ATTR_UNIT_OF_MEASUREMENT,\n CONF_NAME, CONF_HOST, CONF_TOKEN, CONF_TIMEOUT, STATE_ON, STATE_OFF,\n STATE_IDLE, )\n\nfrom homeassistant.helpers.event import async_track_state_change\nimport homeassistant.helpers.config_validation as cv\n\n_LOGGER = logging.getLogger(__name__)\n\n# REQUIREMENTS = ['python-miio>=0.3.6']\nREQUIREMENTS = ['https://github.com/rytilahti/python-miio/archive/'\n 'fc5799a05c217be123985f196e71aad57197f11c.zip#'\n 'python-miio']\n\nDEPENDENCIES = ['sensor']\n\nSUCCESS = ['ok']\n\nDEFAULT_TOLERANCE = 0.3\nDEFAULT_NAME = 'Xiaomi AC Companion'\n\nDEFAULT_TIMEOUT = 10\nDEFAULT_RETRY = 3\n\nDEFAULT_MIN_TEMP = 16\nDEFAULT_MAX_TEMP = 30\nDEFAULT_STEP = 1\n\nSTATE_HEAT = 'heat'\nSTATE_COOL = 'cool'\nSTATE_AUTO = 'auto'\n\nSTATE_LOW = 'low'\nSTATE_MEDIUM = 'medium'\nSTATE_HIGH = 'high'\n\nATTR_AIR_CONDITION_MODEL = 'ac_model'\nATTR_AIR_CONDITION_POWER = 'ac_power'\nATTR_SWING_MODE = 'swing_mode'\nATTR_FAN_SPEED = 'fan_speed'\nATTR_LOAD_POWER = 'load_power'\nATTR_LED = 'led'\n\nDEFAULT_OPERATION_MODES = [STATE_HEAT, STATE_COOL, STATE_AUTO, STATE_OFF]\nDEFAULT_SWING_MODES = [STATE_ON, STATE_OFF]\nDEFAULT_FAN_MODES = [STATE_LOW, STATE_MEDIUM, STATE_HIGH, STATE_AUTO]\n\nSUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_TARGET_TEMPERATURE_HIGH |\n SUPPORT_TARGET_TEMPERATURE_LOW | SUPPORT_FAN_MODE |\n SUPPORT_OPERATION_MODE | SUPPORT_SWING_MODE | SUPPORT_ON_OFF)\n\nCONF_SENSOR = 'target_sensor'\nCONF_CUSTOMIZE = 'customize'\n\nSCAN_INTERVAL = timedelta(seconds=15)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_HOST): cv.string,\n vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,\n vol.Required(CONF_SENSOR, default=None): cv.entity_id,\n vol.Optional(CONF_CUSTOMIZE, default=None): dict,\n})\n\n\n# pylint: disable=unused-argument\n@asyncio.coroutine\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Set up the air conditioning companion from config.\"\"\"\n host = config.get(CONF_HOST)\n name = config.get(CONF_NAME) or DEFAULT_NAME\n token = config.get(CONF_TOKEN)\n sensor_entity_id = config.get(CONF_SENSOR)\n customize = config.get(CONF_CUSTOMIZE)\n\n async_add_devices([XiaomiAirConditioningCompanion(\n hass, name, host, token, sensor_entity_id, customize)],\n update_before_add=True)\n\n\nclass XiaomiAirConditioningCompanion(ClimateDevice):\n \"\"\"Representation of a Xiaomi Air Conditioning Companion.\"\"\"\n\n def __init__(self, hass, name, host, token, sensor_entity_id, customize):\n\n \"\"\"Initialize the climate device.\"\"\"\n self.hass = hass\n self._state = None\n self._state_attrs = {\n ATTR_AIR_CONDITION_MODEL: None,\n ATTR_AIR_CONDITION_POWER: None,\n ATTR_TEMPERATURE: None,\n ATTR_SWING_MODE: None,\n ATTR_FAN_SPEED: None,\n ATTR_OPERATION_MODE: None,\n ATTR_LOAD_POWER: None,\n ATTR_LED: None,\n }\n self._air_condition_model = None\n\n self._name = name if name else DEFAULT_NAME\n self._unit_of_measurement = TEMP_CELSIUS\n self._host = host\n self._token = token\n self._sensor_entity_id = sensor_entity_id\n self._customize = customize\n\n self._target_temperature = None\n self._target_humidity = None\n self._current_temperature = None\n self._current_humidity = None\n self._current_swing_mode = None\n self._current_operation = None\n self._current_fan_mode = None\n\n self._operation_list = DEFAULT_OPERATION_MODES\n self._away = None\n self._hold = None\n self._aux = None\n self._target_temperature_high = DEFAULT_MAX_TEMP\n self._target_temperature_low = DEFAULT_MIN_TEMP\n self._max_temp = DEFAULT_MAX_TEMP + 1\n self._min_temp = DEFAULT_MIN_TEMP - 1\n self._target_temp_step = DEFAULT_STEP\n\n if self._customize and ('fan' in self._customize):\n self._customize_fan_list = list(self._customize['fan'])\n self._fan_list = self._customize_fan_list\n else:\n self._fan_list = DEFAULT_FAN_MODES\n\n if self._customize and ('swing' in self._customize):\n self._customize_swing_list = list(self._customize['swing'])\n self._swing_list = self._customize_swing_list\n else:\n self._swing_list = DEFAULT_SWING_MODES\n\n if sensor_entity_id:\n async_track_state_change(\n hass, sensor_entity_id, self._async_sensor_changed)\n sensor_state = hass.states.get(sensor_entity_id)\n if sensor_state:\n self._async_update_temp(sensor_state)\n\n from miio import AirConditioningCompanion\n _LOGGER.info(\"initializing with host %s token %s\", self._host,\n self._token)\n self._climate = AirConditioningCompanion(self._host, self._token)\n\n @callback\n def _async_update_temp(self, state):\n \"\"\"Update thermostat with latest state from sensor.\"\"\"\n unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)\n\n try:\n self._current_temperature = self.hass.config.units.temperature(\n float(state.state), unit)\n except ValueError as ex:\n _LOGGER.error('Unable to update from sensor: %s', ex)\n\n @asyncio.coroutine\n def _async_sensor_changed(self, entity_id, old_state, new_state):\n \"\"\"Handle temperature changes.\"\"\"\n if new_state is None:\n return\n self._async_update_temp(new_state)\n\n @asyncio.coroutine\n def _try_command(self, mask_error, func, *args, **kwargs):\n \"\"\"Call a AC companion command handling error messages.\"\"\"\n from miio import DeviceException\n try:\n result = yield from self.hass.async_add_job(\n partial(func, *args, **kwargs))\n\n _LOGGER.debug(\"Response received: %s\", result)\n\n return result == SUCCESS\n except DeviceException as exc:\n _LOGGER.error(mask_error, exc)\n return False\n\n @asyncio.coroutine\n def async_turn_on(self: ToggleEntity, speed: str = None, **kwargs) -> None:\n \"\"\"Turn the miio device on.\"\"\"\n result = yield from self._try_command(\n \"Turning the miio device on failed.\", self._climate.on)\n\n if result:\n self._state = True\n\n @asyncio.coroutine\n def async_turn_off(self: ToggleEntity, **kwargs) -> None:\n \"\"\"Turn the miio device off.\"\"\"\n result = yield from self._try_command(\n \"Turning the miio device off failed.\", self._climate.off)\n\n if result:\n self._state = False\n\n @asyncio.coroutine\n def async_update(self):\n \"\"\"Update the state of this climate device.\"\"\"\n from miio import DeviceException\n\n try:\n state = yield from self.hass.async_add_job(self._climate.status)\n _LOGGER.debug(\"Got new state: %s\", state)\n\n self._state = state.is_on\n self._state_attrs = {\n ATTR_AIR_CONDITION_MODEL: state.air_condition_model,\n ATTR_AIR_CONDITION_POWER: state.air_condition_power,\n ATTR_TEMPERATURE: state.temperature,\n ATTR_SWING_MODE: state.swing_mode,\n ATTR_FAN_SPEED: state.fan_speed.name,\n ATTR_OPERATION_MODE: state.mode.name,\n ATTR_LOAD_POWER: state.load_power,\n ATTR_LED: state.led,\n }\n\n if self._air_condition_model is None:\n self._air_condition_model = state.air_condition_model\n\n self._current_operation = state.mode.name.lower()\n # BUG? The target_temperature shoudn't be updated here.\n # It's fine if state.temperature contains the target temperature.\n # self._target_temperature = state.temperature\n\n if (not self._customize) or (self._customize\n and 'fan' not in self._customize):\n self._current_fan_mode = state.fan_speed.name.lower()\n\n if (not self._customize) or (self._customize\n and 'swing' not in self._customize):\n self._current_swing_mode = \\\n STATE_ON if state.swing_mode else STATE_OFF\n\n if not self._sensor_entity_id:\n self._current_temperature = state.temperature\n\n except DeviceException as ex:\n self._state = None\n _LOGGER.error(\"Got exception while fetching the state: %s\", ex)\n\n @property\n def supported_features(self):\n \"\"\"Return the list of supported features.\"\"\"\n return SUPPORT_FLAGS\n\n @property\n def min_temp(self):\n \"\"\"Return the minimum temperature.\"\"\"\n return self._min_temp\n\n @property\n def max_temp(self):\n \"\"\"Return the maximum temperature.\"\"\"\n return self._max_temp\n\n @property\n def target_temperature_step(self):\n \"\"\"Return the target temperature step.\"\"\"\n return self._target_temp_step\n\n @property\n def should_poll(self):\n \"\"\"Return the polling state.\"\"\"\n return True\n\n @property\n def name(self):\n \"\"\"Return the name of the climate device.\"\"\"\n return self._name\n\n @property\n def available(self):\n \"\"\"Return true when state is known.\"\"\"\n return self._state is not None\n\n @property\n def temperature_unit(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return self._unit_of_measurement\n\n @property\n def current_temperature(self):\n \"\"\"Return the current temperature.\"\"\"\n return self._current_temperature\n\n @property\n def target_temperature(self):\n \"\"\"Return the temperature we try to reach.\"\"\"\n return self._target_temperature\n\n @property\n def target_temperature_high(self):\n \"\"\"Return the upper bound of the target temperature we try to reach.\"\"\"\n return self._target_temperature_high\n\n @property\n def target_temperature_low(self):\n \"\"\"Return the lower bound of the target temperature we try to reach.\"\"\"\n return self._target_temperature_low\n\n @property\n def current_humidity(self):\n \"\"\"Return the current humidity.\"\"\"\n return self._current_humidity\n\n @property\n def target_humidity(self):\n \"\"\"Return the humidity we try to reach.\"\"\"\n return self._target_humidity\n\n @property\n def current_operation(self):\n \"\"\"Return current operation ie. heat, cool, idle.\"\"\"\n return self._current_operation\n\n @property\n def operation_list(self):\n \"\"\"Return the list of available operation modes.\"\"\"\n return self._operation_list\n\n @property\n def is_away_mode_on(self):\n \"\"\"Return if away mode is on.\"\"\"\n return self._away\n\n @property\n def current_hold_mode(self):\n \"\"\"Return hold mode setting.\"\"\"\n return self._hold\n\n @property\n def is_aux_heat_on(self):\n \"\"\"Return true if aux heat is on.\"\"\"\n return self._aux\n\n @property\n def current_fan_mode(self):\n \"\"\"Return the current fan mode.\"\"\"\n return self._current_fan_mode\n\n @property\n def fan_list(self):\n \"\"\"Return the list of available fan modes.\"\"\"\n return self._fan_list\n\n @property\n def is_on(self) -> bool:\n \"\"\"Return True if the entity is on\"\"\"\n return self._state\n\n @asyncio.coroutine\n def async_set_temperature(self, **kwargs):\n \"\"\"Set target temperature.\"\"\"\n if kwargs.get(ATTR_TEMPERATURE) is not None:\n self._target_temperature = kwargs.get(ATTR_TEMPERATURE)\n\n if kwargs.get(ATTR_TARGET_TEMP_HIGH) is not None and \\\n kwargs.get(ATTR_TARGET_TEMP_LOW) is not None:\n self._target_temperature_high = kwargs.get(ATTR_TARGET_TEMP_HIGH)\n self._target_temperature_low = kwargs.get(ATTR_TARGET_TEMP_LOW)\n\n if kwargs.get(ATTR_OPERATION_MODE) is not None:\n self._current_operation = kwargs.get(ATTR_OPERATION_MODE)\n else:\n if self._target_temperature < self._target_temperature_low:\n self._current_operation = STATE_OFF\n self._target_temperature = self._target_temperature_low\n elif self._target_temperature > self._target_temperature_high:\n self._current_operation = STATE_OFF\n self._target_temperature = self._target_temperature_high\n elif self._current_temperature and (\n self._current_operation == STATE_OFF or\n self._current_operation == STATE_IDLE):\n self._current_operation = STATE_AUTO\n\n self._send_configuration()\n\n @asyncio.coroutine\n def async_set_humidity(self, humidity):\n \"\"\"Set the target humidity.\"\"\"\n self._target_humidity = humidity\n\n @asyncio.coroutine\n def async_set_swing_mode(self, swing_mode):\n \"\"\"Set target temperature.\"\"\"\n self._current_swing_mode = swing_mode\n if self._customize and ('swing' in self._customize) and \\\n (self._current_swing_mode in self._customize['swing']):\n self._send_custom_command(\n self._customize['swing'][self._current_swing_mode])\n else:\n self._send_configuration()\n\n @asyncio.coroutine\n def async_set_fan_mode(self, fan):\n \"\"\"Set the fan mode.\"\"\"\n self._current_fan_mode = fan\n if self._customize and ('fan' in self._customize) and \\\n (self._current_fan_mode in self._customize['fan']):\n self._send_custom_command(\n self._customize['fan'][self._current_fan_mode])\n else:\n self._send_configuration()\n\n @asyncio.coroutine\n def async_set_operation_mode(self, operation_mode):\n \"\"\"Set operation mode.\"\"\"\n self._current_operation = operation_mode\n self._send_configuration()\n\n @property\n def current_swing_mode(self):\n \"\"\"Return the current swing setting.\"\"\"\n return self._current_swing_mode\n\n @property\n def swing_list(self):\n \"\"\"List of available swing modes.\"\"\"\n return self._swing_list\n\n @asyncio.coroutine\n def async_turn_away_mode_on(self):\n \"\"\"Turn away mode on.\"\"\"\n self._away = True\n\n @asyncio.coroutine\n def async_turn_away_mode_off(self):\n \"\"\"Turn away mode off.\"\"\"\n self._away = False\n\n @asyncio.coroutine\n def async_set_hold_mode(self, hold):\n \"\"\"Update hold mode on.\"\"\"\n self._hold = hold\n\n @asyncio.coroutine\n def async_turn_aux_heat_on(self):\n \"\"\"Turn auxillary heater on.\"\"\"\n self._aux = True\n\n @asyncio.coroutine\n def async_turn_aux_heat_off(self):\n \"\"\"Turn auxiliary heater off.\"\"\"\n self._aux = False\n\n def _send_configuration(self):\n from miio.airconditioningcompanion import \\\n Power, OperationMode, FanSpeed, SwingMode, Led\n\n if self._air_condition_model is not None:\n yield from self._try_command(\n \"Sending new air conditioner configuration failed.\",\n self._climate.send_configuration(\n self._air_condition_model,\n Power(int(self._state)),\n OperationMode[self._current_operation.title()],\n self._target_temperature,\n FanSpeed[self._current_fan_mode.title()],\n SwingMode[self._current_swing_mode.title()],\n Led.Off,\n ), False)\n else:\n _LOGGER.error('Model number of the air condition unknown. '\n 'Configuration cannot be sent.')\n\n def _send_custom_command(self, command: str):\n if command[0:2] == \"01\":\n yield from self._try_command(\n \"Sending new air conditioner configuration failed.\",\n self._climate.send_command(command), False)\n else:\n # Learned infrared commands has the prefix 'FE'\n yield from self._try_command(\n \"Sending new air conditioner configuration failed.\",\n self._climate.send_ir_code(command), False)\n","sub_path":"custom_components/climate/xiaomi_miio.py","file_name":"xiaomi_miio.py","file_ext":"py","file_size_in_byte":17121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"384211765","text":"\"\"\"\nSTEP 2: CROSS TRAINING\nThe GDNN models are trained.\n\"\"\"\nfrom s0_start import basedir\nimport sys \nsys.path.append(basedir)\n\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom os.path import join\n\nfrom ninolearn.utils import include_time_lag\nfrom ninolearn.IO.read_processed import data_reader\nfrom ninolearn.learn.models.dem import DEM\nfrom ninolearn.learn.fit import cross_training\nfrom ninolearn.pathes import infodir\n\n\n# =============================================================================\n# Determine the end of observational period and the lead times\n# =============================================================================\nfrom s0_start import start_pred_y, start_pred_m\nf = open(join(infodir,\"enddate.txt\"), \"r\")\nendyr = f.readline()\nendmth = f.readline()\nf.close()\nend_obs_m = int(endmth)\nend_obs_y = int(endyr)\n\nif end_obs_m < 10:\n endmth = '0'+endmth\n\nif start_pred_y > end_obs_y+1 or (start_pred_y > end_obs_y and start_pred_m > end_obs_m):\n raise ValueError(\"More than 1 year difference between end of observations and start of predictions.\\\n Either include more observations or let the predictions start earlier.\")\n\nlt_first = (start_pred_m - end_obs_m)%12 - 1 \nlead_times = np.arange(lt_first,lt_first+9) # prediction for 9 seasons\nnp.save(join(infodir,'lead_times'), lead_times)\n\n\n# =============================================================================\n# Process data and train model\n# =============================================================================\n\ndef pipeline(lead_time, return_persistance=False):\n \"\"\"\n Data pipeline for the processing of the data before the Deep Ensemble\n is trained.\n\n :type lead_time: int\n :param lead_time: The lead time in month.\n\n :type return_persistance: boolean\n :param return_persistance: Return as the persistance as well.\n\n :returns: The feature \"X\" (at observation time), the label \"y\" (at lead\n time), the target season \"timey\" (least month) and if selected the\n label at observation time \"y_persistance\". Hence, the output comes as:\n X, y, timey, y_persistance.\n \"\"\" \n reader = data_reader(startdate='1960-01', enddate=endyr+'-'+endmth)\n\n # indices\n oni = reader.read_csv('oni')\n dmi = reader.read_csv('dmi')\n wwv = reader.read_csv('wwv_proxy')\n\n # seasonal cycle\n cos = np.cos(np.arange(len(oni))/12*2*np.pi)\n\n # wind stress\n taux = reader.read_netcdf('taux', dataset='NCEP', processed='anom')\n\n taux_WP = taux.loc[dict(lat=slice(2.5,-2.5), lon=slice(120, 160))]\n taux_WP_mean = taux_WP.mean(dim='lat').mean(dim='lon')\n\n # include values from 3 and 6 months previously as predictor variables\n n_lags = 3\n step = 3\n\n # shift such that lead time corresponds to the definition of lead time\n shift = 3\n\n # process features\n feature_unscaled = np.stack((oni,\n wwv,\n dmi,\n cos,\n taux_WP_mean\n ), axis=1)\n\n # scale each feature\n scalerX = StandardScaler()\n Xorg = scalerX.fit_transform(feature_unscaled)\n\n # set nans to 0.\n Xorg = np.nan_to_num(Xorg)\n np.save(join(infodir,'Xorg'), Xorg) \n\n # arange the feature array\n X = Xorg[:-lead_time-shift,:]\n X = include_time_lag(X, n_lags=n_lags, step=step)\n\n # arange label\n yorg = oni.values\n y = yorg[lead_time + n_lags*step + shift:]\n\n # get the time axis of the label\n timey = oni.index[lead_time + n_lags*step + shift:]\n\n if return_persistance:\n y_persistance = yorg[n_lags*step: - lead_time - shift]\n return X, y, timey, y_persistance\n\n else:\n return X, y, timey\n\nif __name__==\"__main__\":\n cross_training(DEM, pipeline, 1, lead_times,\n layers=1, neurons = 32, dropout=0.05, noise_in=0.0, noise_sigma=0.,\n noise_mu=0., l1_hidden=0.0, l2_hidden=0.,\n l1_mu=0, l2_mu=0., l1_sigma=0,\n l2_sigma=0.0, lr=0.01, batch_size=100,\n epochs=5000, n_segments=5, n_members_segment=3, patience=25,\n activation='tanh',\n verbose=0, pdf=\"normal\", name=\"gdnn_ex_pca\")\n \nprint(\"\\n \\nStep 2 finished, continue to step 3!\")","sub_path":"predictions/s2_training.py","file_name":"s2_training.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"622852777","text":"# coding: utf-8\nfrom __future__ import print_function, unicode_literals\n\nimport os\nimport sys\nfrom strip_hints import strip_file_to_string\n\n\n# list unique types used in hints:\n# rm -rf unt && cp -pR copyparty unt && (cd unt && python3 ../scripts/strip_hints/a.py)\n# diff -wNarU1 copyparty unt | grep -E '^\\-' | sed -r 's/[^][, ]+://g; s/[^][, ]+[[(]//g; s/[],()<>{} -]/\\n/g' | grep -E .. | sort | uniq -c | sort -n\n\n\ndef pr(m):\n sys.stderr.write(m)\n sys.stderr.flush()\n\n\ndef uh(top):\n if os.path.exists(top + \"/uh\"):\n return\n\n # pr(\"building support for your python ver\")\n pr(\"unhinting\")\n files = []\n for (dp, _, fns) in os.walk(top):\n for fn in fns:\n if not fn.endswith(\".py\"):\n continue\n\n fp = os.path.join(dp, fn)\n files.append(fp)\n\n try:\n import multiprocessing as mp\n\n with mp.Pool(os.cpu_count()) as pool:\n pool.map(uh1, files)\n except Exception as ex:\n print(\"\\nnon-mp fallback due to {}\\n\".format(ex))\n for fp in files:\n uh1(fp)\n\n pr(\"k\\n\")\n with open(top + \"/uh\", \"wb\") as f:\n f.write(b\"a\")\n\n\ndef uh1(fp):\n pr(\".\")\n cs = strip_file_to_string(fp, no_ast=True, to_empty=True)\n\n # remove expensive imports too\n lns = []\n on = True\n for ln in cs.split(\"\\n\"):\n if ln.startswith(\"if True:\"):\n on = False\n continue\n\n if not on and (not ln.strip() or ln.startswith(\" \")):\n continue\n\n on = True\n lns.append(ln)\n\n cs = \"\\n\".join(lns)\n with open(fp, \"wb\") as f:\n f.write(cs.encode(\"utf-8\"))\n\n\nif __name__ == \"__main__\":\n uh(\".\")\n","sub_path":"scripts/strip_hints/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}
+{"seq_id":"50676601","text":"import os\nfrom flask import (\n Flask, flash, render_template,\n redirect, request, session, url_for)\nfrom flask_pymongo import PyMongo\nfrom bson.objectid import ObjectId\nfrom werkzeug.security import generate_password_hash, check_password_hash \nif os.path.exists(\"env.py\"):\n import env\n\n\napp = Flask(__name__)\n\napp.config[\"MONGO_DBNAME\"] = os.environ.get(\"MONGO_DBNAME\")\napp.config[\"MONGO_URI\"] = os.environ.get(\"MONGO_URI\")\napp.secret_key = os.environ.get(\"SECRET_KEY\")\n\nmongo = PyMongo(app)\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/get_inventories\")\ndef get_inventories():\n inventories = list(mongo.db.inventories.find().sort(\"category_name\", 1))\n inventories = list(mongo.db.inventories.find().sort(\"inventory_name\", 1))\n return render_template(\"inventories.html\", inventories=inventories)\n\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if request.method == \"POST\":\n # check if username already exists in the db\n existing_user = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\").lower()})\n\n if existing_user:\n flash(\"Username already exists\")\n return redirect(url_for(\"register\"))\n\n register = {\n \"username\": request.form.get(\"username\").lower(),\n \"password\": generate_password_hash(request.form.get(\"password\"))\n }\n mongo.db.users.insert_one(register)\n\n # put the new user into 'session' cookie\n session[\"user\"] = request.form.get(\"username\").lower()\n flash(\"Registration Successful!\")\n return redirect(url_for(\"profile\", username=session[\"user\"]))\n return render_template(\"register.html\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"POST\":\n # check if username exists in db\n existing_user = mongo.db.users.find_one(\n {\"username\": request.form.get(\"username\").lower()})\n\n if existing_user:\n # ensure hashed password matches user input\n if check_password_hash(\n existing_user[\"password\"], request.form.get(\"password\")):\n session[\"user\"] = request.form.get(\"username\").lower()\n flash(\"Welcome, {}\".format(\n request.form.get(\"username\")))\n return redirect(url_for(\n \"profile\", username=session[\"user\"]))\n else:\n # invalid password match\n flash(\"Incorrect Username and/or Password\")\n return redirect(url_for(\"login\"))\n\n else:\n # username doesn't exist\n flash(\"Incorrect Username and/or Password\")\n return redirect(url_for(\"login\"))\n\n return render_template(\"login.html\")\n\n\n@app.route(\"/profile/\", methods=[\"GET\", \"POST\"])\ndef profile(username):\n # get the session user's username from db\n username = mongo.db.users.find_one(\n {\"username\": session[\"user\"]})[\"username\"]\n return render_template(\"profile.html\", username=username)\n\n\n@app.route(\"/logout\")\ndef logout():\n # remove user from session cookies\n flash(\"You have been logged out\")\n session.pop(\"user\")\n return redirect(url_for(\"login\"))\n\n\n@app.route(\"/add_inventory\", methods=[\"GET\", \"POST\"]) \ndef add_inventory():\n if request.method == \"POST\":\n inventory = {\n \"category_name\": request.form.get(\"category_name\"),\n \"inventory_name\": request.form.get(\"inventory_name\"),\n \"inventory_description\": request.form.get(\"inventory_description\"),\n \"created_by\": session[\"user\"]\n }\n mongo.db.inventories.insert_one(inventory)\n flash(\"Word Successfully Added\")\n return redirect(url_for(\"get_inventories\"))\n \n categories = mongo.db.categories.find().sort(\"category_name\", 1)\n return render_template(\"add_inventory.html\", categories=categories)\n\n\n@app.route(\"/edit_inventory/\", methods=[\"GET\", \"POST\"])\ndef edit_inventory(inventory_id):\n if request.method == \"POST\":\n submit = {\n \"category_name\": request.form.get(\"category_name\"),\n \"inventory_name\": request.form.get(\"inventory_name\"),\n \"inventory_description\": request.form.get(\"inventory_description\"),\n \"created_by\": session[\"user\"]\n }\n mongo.db.inventories.update({\"_id\": ObjectId(inventory_id)}, submit)\n flash(\"Word Successfully Updated\")\n\n inventory = mongo.db.inventories.find_one({\"_id\": ObjectId(inventory_id)})\n categories = mongo.db.categories.find().sort(\"category_name\", 1)\n return render_template(\n \"edit_inventory.html\", inventory=inventory, categories=categories)\n\n\n@app.route(\"/delete_inventory/